Compare commits

...
46 Commits
Author SHA1 Message Date
cflmy f666eaaf40 release: v1.5.0
Foreign v2 + document-native notebooks, view contrast/themes/resize, public OKF/EKC and Python examples. Bump CLI/wasm/ext to 1.5.0; no core surface delta.
2026-10-18 03:17:53 +08:00
cflmy e6f05c7748 docs(public): showcase foreign v2, OKF and EKC
Rewrite the public foreign reference, add bilingual complex Python notebook and OKF/EKC pages, and expand both homepages with executable foreign, notebook, knowledge and preflight examples.
2026-10-18 03:15:34 +08:00
cflmy 81f9ea0072 fix(view): map document tokens to the active theme
Legacy view tokens (--ink, --fill, --line, --muted) now resolve from the notebook theme. This fixes dark text and white annotation chips on the dark STRUCTURE surface, including function names, binding labels, tables, and the right rail.
2026-10-18 03:05:29 +08:00
cflmy dbf3f3a14b fix(view): raise code contrast and unify syntax colors
Remove the two conflicting highlight.js stylesheets and define one high-contrast token palette. Dark code foreground is #f0f0f0 on #1e1e1e (14.6:1); light is #24292f on #f6f8fa (13.8:1). Keywords, strings, and comments stay above readable contrast, and base view code blocks are resizable too.
2026-10-18 03:03:08 +08:00
cflmy 654e89d98c style(view): make cell resize affordance visible
Style the native vertical resize grip and add a hover hint on code and output panes.
2026-10-18 02:59:36 +08:00
cflmy be20629496 feat(view): resizable cells and light/dark themes
Add native vertical resize to code and output panes; add a VS Code Light token set with Jupyter light syntax highlighting, a toolbar theme toggle, and localStorage persistence. Keep the restored three-column layout.
2026-10-18 02:59:21 +08:00
cflmy 3223295841 fix(view): restore notebook left nav and right rail
Keep the original three-column layout (file navigation, main structure, Functions/Variables rail) and execution/source sections; restyle them with the same VS Code dark surface tokens so the notebook remains readable and consistent.
2026-10-18 02:56:34 +08:00
cflmy beb5bdbe8c style(view): align notebook with VS Code dark and Jupyter cells
Flat VS Code Dark surfaces and borders, Jupyter In[n]/Out[] cell structure, unified top cell toolbar, consistent typography and spacing, removed gradients, glows, heavy shadows, and multi-color pills.
2026-10-18 02:51:28 +08:00
cflmy b8cb022018 style(view): redesign notebook layout and controls
Single-column notebook shell, sticky glass toolbar, card cells with language/kernel/status pills, output panel, dark-mode support, responsive layout, and hidden duplicate Execution/Source sections.
2026-10-18 02:45:10 +08:00
cflmy b9e331cb31 test(notebook): add Python business-insights example
Five-cell Python notebook sharing one kernel: deterministic order generation, regional/product metrics, z-score anomaly detection, ASCII report + JSON, and an isolated second Python kernel that validates the report through an explicit file bridge.
2026-10-18 02:38:48 +08:00
cflmy 476c2b607b fix(view): use relative API URLs for path-prefix reverse proxy
Notebook and debugger controls now call api/... and open debug?path=... relative to the page, so the same HTML works under a path prefix such as /marqdo-view/<token>/. This enables same-origin DSH preview without publishing another Docker port.
2026-10-18 02:33:50 +08:00
cflmy d99b275336 fix(parse): do not over-promote branch-local variables to params
If/else arms that all bind a local (e.g. # llm key/url/mdl/nm) no longer leak it into constructor params. This fixes the missing `key` error in llm.create and restores the agent/llm gold tests. Adds a regression test.
2026-10-18 02:09:16 +08:00
cflmy 1415aee08f docs(notebook): record D1–D3 implementation status 2026-10-18 01:45:41 +08:00
cflmy 0f2c12b636 feat(notebook): link statement debugger from view
Expose /debug and /api/debug/* on the live view server; add a notebook Debug button so Marqdo statement stepping is reachable from the same page/session as cell stepping.
2026-10-18 01:44:05 +08:00
cflmy 9873df7099 feat(notebook): reload, journal and state panel polish
D3 (partial): reload re-parses the document while preserving kernels, marks changed cells dirty; Journal and Reload view actions; filtered Node variable names for the state panel; per-session timeout parsing before spawn.
2026-10-18 01:41:36 +08:00
cflmy 3001ed7ba5 feat(notebook): document session with shared kernels and view controls
D1/D2: 内核表/会话表 parsing, DocumentSession cell index, named/default kernels, shared state + isolation, run_cell/step/run_all/restart/assign, state bridge, journal, POST /api/session/*, and a live-view notebook bar with status badges, per-cell kernel selector, step/run-all and push/pull state form.
2026-10-18 01:39:36 +08:00
cflmy 050d71927f feat(foreign): persistent Python/Node kernels and state bridge
F3/F3.5: session_open/eval/close/list, session_set/get/names, Python and Node bootstraps, strict serial protocol, per-session timeout, crash isolation, drop cleanup, and node/bash gold tests (python conditional).
2026-10-18 01:32:48 +08:00
cflmy 7859170aec feat(foreign): JSON call and parallel fan-out
F2: call/call_many JSON bridge, run_many ordered parallel execution with per-item isolation and concurrency cap, plus node gold tests for call and call_many.
2026-10-18 01:29:15 +08:00
cflmy e32ff8f6b3 feat(foreign): structured invoke, presets, probe and config
F0/F1: safe execution core (exec gate, bounded IO, process-group timeout), structured invoke records, run options, 15 language presets, register/unset/probe/config, view stderr/exit/ms, and node/bash gold tests.
2026-10-18 01:26:53 +08:00
cflmy c21a28c3bc docs(foreign): design kernel runtime and document session
Record the Jupyter-beyond discussion, decisions, and the document-native notebook syntax (内核表/会话表). Split the design into F (foreign kernel runtime) and D (document session) layers, with roadmaps, state bridge, stepping, journal, and security rules.
2026-10-18 00:43:31 +08:00
cflmyandCursor 1e61dca9d8 release: Marqdo 1.4.6
CLI and wasm only. Bare self-increment now promotes a required parameter, matching design §8.2. Extension pack stays 1.4.5.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 23:58:09 +08:00
cflmyandCursor ba675a4767 fix(parse): promote a bare self-increment to a required parameter.
Design §8.2 treats the first bold assignment as a declaration, but merging only walked backtick mentions, so n = n + 1 never entered the signature.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 23:55:30 +08:00
cflmyandCursor bfd468d5e3 release: Marqdo 1.4.5
Streamable HTTP MCP, web invoke Bearer/401, openai/agent json.get hardening.
Bump CLI/Ext/wasm and debian changelog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:36:07 +08:00
cflmyandCursor 8353ba38fe Add Streamable HTTP MCP and harden web /v1 invoke auth.
agent_mcp_serve gains http transport; invoke injects Bearer/X-Api-Key and maps
unauthorized to 401; openai/agent field access prefers json.get over footnotes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:33:24 +08:00
cflmyandCursor b43a08b2e2 release: Marqdo 1.4.4
Soft LLM transport errors and table-first ext/ai; CLI + Ext + wasm SemVer bump.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 14:38:16 +08:00
cflmyandCursor 1908bf1a53 fix(ai): soft LLM transport errors and strip ext/ai json glue
Host/plugin HTTP failures return structured finish|status=error instead of
aborting the VM; agent/llm/openai/智能体 result maps use GFM tables and
table.put. SKILL gains positive copy-paste examples so agents stop mirroring
legacy json.set chains.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 14:27:45 +08:00
cflmyandCursor c44ea38ae2 release: Ext pack 1.4.3 — agent.run cold EFI / resolve llm_free
Bump ext/VERSION only (CLI stays 1.4.2). Ships agent facade + native miss-field fix for qdagent cold OKF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:56:40 +08:00
cflmyandCursor d489f7c088 fix(ext/ai): cold agent.run EFI — self.preflight and resolve llm_free
Miss resolve omitted llm_free and run called bare preflight, which crashed
qdagent on empty OKF. Align miss fields, use self.preflight + json.get, add
regression gold and research note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:54:00 +08:00
cflmyandCursor a993cfd76a chore: sync Cargo.lock package versions to 1.4.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:21:23 +08:00
cflmyandCursor d5f826a8c8 release: Marqdo 1.4.2
Bump CLI/wasm/ext to 1.4.2 for Agent/LLM optimize O1–O5 (sandbox trial,
promote proof, step_route/EFI, lint, quarantine).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:51:41 +08:00
cflmyandCursor 0f72173d08 feat(ext/ai): land Agent/LLM optimize waves O1–O5
Wire opt-in sandbox trial into agent, require sandbox proof before OKF
promote, add step_route/EFI/cost surfaces, style lint + quarantine, and
offline policy optimize script—keeping GFM tables over json glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:47:28 +08:00
cflmyandCursor a707758d47 docs: research and plan Agent/LLM optimization with OKF and sandbox
Capture the 2026-10 landscape (skills, Skill Lift, routing, GEPA) against Marqdo’s code-as-docs assets and list feasible optimize directions without editing doc/next.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:13:48 +08:00
cflmyandCursor 63bcb882a6 feat(ext/ai): add CoW sandbox for Marqdo-only agent trials
Give agents a capability-capped run path that stages workspace edits until commit, so generated .mq.md can be verified without polluting the real tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:11:54 +08:00
cflmyandCursor 1bb16dd6db release: Marqdo 1.4.1
View annot leaders mid-to-mid SVG, frame chip id unify; bump CLI/wasm/ext.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:37:24 +08:00
cflmyandCursor 58ec2172d6 fix(view): mid-to-mid annot leaders and prose chip density
Unify frame chip ids with marks, reorder chips under anchors, and draw
SVG leaders from underline mid-bottom to chip mid-top so crowded bands
stay readable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:36:12 +08:00
cflmyandCursor 66926e9e0a release: Marqdo 1.4.0
Prose-unified control flow, formula meta bind, image writeback, view
inferred params; sync CLI/wasm/ext/VERSION and install docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:54:45 +08:00
cflmyandCursor dcf4c05663 fix(ext/net): wrap url.encode via lib/net, not host_*
Gold rule bans host_* from ext/**; encode must go through stdlib.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:47:07 +08:00
cflmyandCursor f47a1e143a feat(writeback): image form ![marqdo-out](…) with view parity
Auto-persist image paths/URLs as Markdown images (validated extension);
keep HTML comment for text. View and static export share styled source
markers and output-card <img> rendering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:45:52 +08:00
cflmyandCursor 9cf98a98b5 feat: block formula meta bind and control-flow prose
Support $$ % marqdo: var= binding, arm/loop narrative (fix comment-paragraph
swallow of branch arms), foreach ZH/EN sugar, and condition-line narrative.
Welcome pages and gold samples updated; view skips meta formula fence bodies.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:28:46 +08:00
cflmyandCursor f99d552d87 feat(view): show inferred param values; migrate welcome to v0.3 prose
Param chips carry call-frame values (and refresh with the call picker).
Welcome pages and the marqdo skill prefer body-inferred, conversational markup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:32:50 +08:00
cflmyandCursor 7d49c358c1 fix(view): nested-call welcome + clean formula/code cards
Welcome pages put greet calls in # main so CallFrames/pickers appear;
document surface skips fence body lines and Bind chips under formula/code cards.
Adds view-static-interactive design and entry-vs-method regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:13:42 +08:00
cflmyandCursor a32c0cd78f fix(ppa): skip cp when local orig already sits in build-area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:42:37 +08:00
cflmyandCursor 0a8f76d9b4 release: v1.3.3 — view document-surface Structure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:18:51 +08:00
cflmyandCursor 4e2419b598 feat(view): document-surface Structure with frame-aware annotations
Browse Structure keeps narration and surfaces post-stmt values, branch
arms, and call/loop pickers; static `view output` shares the same render
path so exported HTML matches live view.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:12:53 +08:00
cflmy f6374d1593 release: ext pack v1.3.2 trailing slash route fix 2026-10-13 15:37:42 +08:00
cflmy 9ede4bc63d fix(web): strip trailing slash so /post/foo/ matches /post/foo
Go ServeMux does exact-match routing; a trailing slash caused dynamic
routes like /post/{slug} to fall through to the 404 catch-all. Add
withStripTrailingSlash middleware as the outermost handler wrapper so
all downstream middleware (RBAC, tenant, mux) see the normalized path.

Tested: static routes, dynamic routes, root path, query-string preservation.
2026-10-13 15:24:26 +08:00
149 changed files with 20278 additions and 1205 deletions

No files matched your search

+55 -3
View File
@@ -38,7 +38,7 @@ A `.mq.md` file must stay readable as Markdown. If a human cannot skim the data
Cells are expressions (`doc/design/table-cell-expressions.md`): bare words = text, `` `var` `` = variable, quote paths/`/` ratios.
### 2. Good patterns
### 2. Good patterns (copy these — not `json.set`)
**Wire / steps / commands** — `@` record table:
@@ -60,7 +60,53 @@ Cells are expressions (`doc/design/table-cell-expressions.md`): bare words = tex
| `wire` | `set_text` |
```
**Single dynamic key** — one `table.put` (or a helper), not a json chain:
**Agent / LLM result map** — one readable row, not a `json.parse` + `json.set` chain:
```markdown
`out` =
| status | task | result | llm_calls | tokens |
|--------|------|--------|-----------|--------|
| ok | `task` | `reply` | `llm_calls` | `tokens` |
*out*
```
**Soft error pack** (transport / gate failure) — still a table humans can skim:
```markdown
`pack` =
| finish | text | error | usage | tool_calls |
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
```
**Optional / conditional key** — sparse `table.put` after the static table (one dynamic key only):
```markdown
`out` =
| status | task |
|--------|------|
| error | `task` |
1. `err`
**out = > table.put in=`out` at="error" value=`err`**
2. *
**_ = 1**
```
**Empty list / empty map** — prefer stdlib seeds over `json.parse text=[]` / `{}`:
```markdown
**empty_tc = > table.empty_list**
**empty_map = > table.empty_map**
```
**Single dynamic key from scratch** — one `table.put` (or a helper), not a json chain:
```markdown
**`set_text` = table.put in=None at="#log" value=msg**
@@ -73,14 +119,20 @@ Better still — call a named helper:
**browser.set_text sel="#log" text=msg**
```
### 3. Bad pattern (do not write)
**When `json.*` is OK:** `json.parse` / `json.stringify` / `json.quote` on **wire text**; `json.get` to read an opaque map. Never use `json.set` / `json.append` to *build* author-facing structures.
### 3. Bad pattern (do not write — and do not copy from old `ext/ai`)
```markdown
**`ret` = json.set map=None key="set_text" value=…**
**`ret` = json.set map=ret key="canvas" value=…**
**`cmds` = json.append list=cmds item=c0**
**`out` = json.parse text={"status":"ok"}**
**`out` = json.set map=out key="task" value=task**
```
Matching surrounding **legacy** `json.set` in `ext/ai/*.mq.md` is **not** compliance. Refactor the call site to tables / `table.put` instead of extending the glue.
## Writing application `.mq.md`
1. Frontmatter: title + imports (`table`, domain libs). **Do not import `json` unless parsing strings.**
+49 -151
View File
@@ -4,95 +4,40 @@ description: >-
Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose,
importing lib/* or ext/web or ext/quantum or ext/linalg, running marqdo CLI,
building dynamic sites with ext/web, quantum circuits with ext/quantum,
formula-first linear algebra with ext/linalg, or when the user mentions
Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, quantum/量子,
or linalg/线性代数 extension.
importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic
sites with ext/web, quantum circuits with ext/quantum, or when the user
mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or
quantum/量子 extension.
---
# Marqdo development
Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python.
Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-mapping-v0.3.md) (**v0.3 · runtime**), `doc/design/keywords.md`. Legacy v0.2 notes: `doc/design/markdown-mapping.md` (historical). Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets, **ext → R2+GitHub**, **CLI → Ubuntu PPA**): use [marqdo-release](../marqdo-release/SKILL.md) — detect versions, **ask for SemVer + mode (`full` / `cli` / `ext`)**, then follow that playbook. Ext-only releases are allowed. If sudo/GPG/PPA steps need the user, print the exact commands.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text="…"**` / `> 打印 内容=…`.
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is **not** code-shaped (`**说明**`, mid-line `*only*`) is ignored — see [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md). Dead `` `名` `` (never read) is OK and does not become a param.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text="hi"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.
2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**.
3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
12. **Bracket-marked calls:** Function name may be marked with `[函数名]`; bare words before `[` are boolean modifiers (`礼貌 [问候] x` → `礼貌=True`). `]` immediately followed by `(` is **index** `[key](coll)`, not a call. Prefer `[k](c)` over footnote index in new code. See [bracket-call-modifiers.md](../../doc/design/bracket-call-modifiers.md).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code. **Positive copy-paste shapes** (result map, soft-error pack, sparse `table.put`): [marqdo-dev](../marqdo-dev/SKILL.md) §2 · [examples.md](examples.md) §6e. Do **not** extend legacy `json.set` in `ext/ai` — refactor to tables.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## 记不住语法细节?查 MLSP(AI 必读)
**不必背 Marqdo 语法细节**——语法可查、程序可验、修复有界。写码前后走**查询式**工作流:
```bash
printf '%s\n' '{"id":1,"method":"syntax","params":{"query":"返回"}}' | marqdo mlsp
printf '%s\n' '{"id":2,"method":"locate","params":{"path":"a.mq.md","symbol":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":3,"method":"validate","params":{"path":"a.mq.md"}}' | marqdo mlsp
printf '%s\n' '{"id":4,"method":"schema","params":{"path":"a.mq.md","unit":"加一"}}' | marqdo mlsp
printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_mismatch","doc_anchor":"a.mq.md#L9-L15"}}' | marqdo mlsp
```
| method | 何时用 |
|--------|--------|
| `syntax` | 不确定某个语法怎么写(关键字/别名 → 构造卡片:「返回」「表」「调用」「循环」…) |
| `locate` | 找符号定义位置 + 契约;或反查构造卡片 |
| `validate` | 提交前校验(结构化诊断数组;`ok:false` 就修) |
| `schema` | 查单元契约(形参/返回/字段) |
| `repair_targets` | 拿错误的**有界**修复靶点:只改锚点范围内行,越界必弃权(abstain) |
行分隔 JSON:每行请求 `{"id","method","params"}` → 每行响应 `{"id","ok","result"|"error"}`。
语法唯一事实来源 = `doc/design/core-surface.md`(CI 守卫同步);卡片带 `manual` 指回文档行。
所有错误诊断都是结构化 JSON:`code` / `severity` / `span` / `suggestion` / `doc_anchor` / `doc_quote` / `contract_ref`。
### 渐进式契约(可选标注;schema 就长在文档表里)
契约是**未绑定文档表**(绑定表是数据,永远不是契约)。三种形状、严格位置:
| 形状(须含 `类型` 列) | 允许位置 | 附着 |
|--------------------------|----------|------|
| `参数`/`类型`/`说明` 表 + `返回`/`类型`/`说明` 表 | 函数体首个可执行行之前 | 函数 |
| `字段`/`类型`/`可空`/`说明` 表 | 紧邻 `` `名` = `` 绑定之前 | 集合(变量) |
| `字段`/`类型`/`可空`/`说明` 表 | 对象(`#`)体首成员之前 | 对象类型 |
````text
## 加一
对于输入变量`n`,期望是数字。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 输入值 |
| 返回 | 类型 | 说明 |
|------|------|------|
| | number | 加一结果 |
*n+1*
````
- 类型词汇:`text` / `number` / `bool` / `list` / `map` / `any` / `#` 对象名(拼错 ⇒ `contract.unknown_type` + 最近建议)。
- 契约表**永不执行**、不污染升参推断;无契约文件行为逐字节不变(动态默认,零摩擦)。
- 运行时只在四个边界校验:调用实参 / 字段访问 `[键](集合)` / 表绑定 / 返回。
- `marqdo check [FILE] [--json]` 静态互查:契约行 vs 升参推断形参**双向**漂移(错行=Error;新升参未覆盖=Warning)、未知类型、错位契约;有 Error 非零退出。
- 契约诊断带 `doc_anchor` + `doc_quote`(表原文)——修复只照锚点局部改。
## Markup → meaning (v0.3)
## Markup → meaning (v0.2)
| Marker | Meaning |
|--------|---------|
@@ -103,14 +48,13 @@ printf '%s\n' '{"id":5,"method":"repair_targets","params":{"code":"contract.arg_
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `修饰 [fn] args` | Bracket-marked call; leading words → `名=True` |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
| `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
| `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
| `****` or `**` + spaces + `**` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
@@ -159,17 +103,17 @@ Chinese builtins (same functions, no import):
## Statements, returns, branches
```markdown
**x = 1**
**y = x + 2**
*x = 1*
*y = x + 2*
## add_one
+ `n`
*n + 1*
**n + 1**
```
```markdown
**n = 0**
*n = 0*
1. `n` > 0
> print text=positive
@@ -192,16 +136,16 @@ import clock:lib/time.mq.md
# main
**xs = > text.str_split s="a,b,c" sep=","**
*xs = > text.split value="a,b,c" sep=","*
> print text=`xs`
**t = > clock.now_unix**
*t = > clock.now_unix*
```
- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum|linalg` (see `doc/design/ext-cli.md`). **`ext/llm`** — intelligence primitive (`ask` / `stream` / `collect`; `complete` is compat); **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below); **`ext/linalg`** — formula-first linear algebra (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
@@ -216,61 +160,24 @@ Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --releas
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only. **Engineering Knowledge(EKC)**:`marqdo knowledge|find|reuse|…` + `agent.preflight`(REUSE→ADAPT→CREATE)——见 [engineering-knowledge.md](../../doc/design/engineering-knowledge.md)。
4. **Skill Compilation (v2)** — successful runs become `.mq.md` episodes; after enough evidence, `maybe_learn` compiles an executable skill (`llm_free`). Prefer `## run` over bare `## plan` when you want learning.
5. **Adaptive Routing (P4)** — router is abstract (`marqdo` / `small-llm` / `llm` / `auto`); `jev` is a compat alias of `small-llm`. Decision via `router_model` (any llm handle). Policy Compilation writes `policies/router.mq.md`.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## run` / `## route` / `## step` / `## plan` (+ `resolve` / `record_episode` / `maybe_learn` / `compile` / `compile_policy` / `metrics`). Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`). Inspect without LLM: `dump_step_context`. Inside `writeback=` / `写回=` branches use `host_writeback_record` (param name shadows the writeback import).
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) · v2: [doc/next/003.md](../../doc/next/003.md) · P4: [doc/next/004.md](../../doc/next/004.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin: `scripts/build-web-plugin.sh` / `marqdo ext add web`.
Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md).
**Constitution (ADR 0007 — do not degrade):**
**Do not degrade:** Document/Endpoint metadata; facade `web.page|route|serve|render|inspect`; View `|type|slot|value|attrs|style|` only; no `compose_*` / `configure` / author `ensure_plugin`. DB → `ext/data`; auth → `ext/security`; net → `ext/net`.
1. **Document / Endpoint / Resource** — `.mq.md` with `type: web|endpoint` (ZH `类型: 网页|端点`) is the site surface; not a Flask-style class pile.
2. **Code is documentation** — the file is docs + route + handler.
3. **Table = data** — View schema only `|type|slot|value|attrs|style|`. No `compose_*` dialects, no `json.set` glue.
4. **Facade only** — `web.page` · `web.route` · `web.serve` · `web.render` · `web.inspect`. DB → `ext/data`; auth → `ext/security`; ws/http → `ext/net`.
5. **No author `ensure_plugin` / `host_*`**; import web = capability (plugin auto-load).
6. **Declared vs system routes**; `web.inspect` lists both. No silent user routes.
Import **one language** per file:
- EN: `import web:ext/web/web.mq.md` (+ `import data:ext/data/db.mq.md` as needed)
- EN: `import web:ext/web/web.mq.md`
- ZH: `导入 网页:ext/web/网页.mq.md`
```markdown
---
type: web
route: /
title: Hello
import web:ext/web/web.mq.md
---
# Hello
Executable document as a page.
```
```markdown
---
type: endpoint
method: POST
path: /api/ping
response: json
---
*{"ok": true}*
```
Site entry may `# main` → `web.serve root="."`. Client WASM: `ext/web/client.mq.md` / `lib/browser` — no author JS.
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · ADR [0007](../../doc/adr/0007-web-document-endpoint.md) · rule: `.cursor/rules/web-artifact-no-degrade.mdc` · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
Web patterns: [examples.md](examples.md) · API index: [reference.md](reference.md).
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
## Official extension: `ext/quantum` (circuits + Q7/Q8)
@@ -296,29 +203,23 @@ Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --relea
Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/).
## Official extension: `ext/linalg` (formula-first LA)
## Foreign kernels (v1.5.0)
Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build --release -p marqdo_plugin_linalg`, then **`marqdo ext add linalg` again** so view loads the new native lib.
`lib/foreign` is now a full foreign-kernel surface, not only `run`:
- EN: `import la:ext/linalg/linalg.mq.md`
- ZH: `导入 la:ext/linalg/线性代数.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards.
APIs (EN): `symbol` → `# matrix`;中缀 `+`/`-`/`*`;方法 `` `A`.T `` / ``.simplify`` / ``.ascii`` · `from_formula` / `explicit` / `factorize` / `draw` · `lstsq` / `norm` / `cond` / `rank`.
Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · formula-doc: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
- `invoke` returns a record (`ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result`); pass `input` for JSON stdin and `output="json"` for a parsed result.
- `call` is JSON-in / JSON-out; `call_many` fans out one program over a list with ordered results.
- `session_open` starts a persistent Python/Node kernel; `session_eval` evaluates source; `session_set` / `session_get` bridge values explicitly as JSON. Close it with `session_close`.
- A notebook is still a document: bind `内核表` and `会话表` as ordinary tables inside `# main`. A `view` session adds cell stepping, Run All, kernel switching, journal and reload. No new Markdown marker exists.
- The same source remains the authority; state crossing kernels is explicit, never implicitly mirrored.
## AI authoring workflow
1. **查再写**:不确定语法就 `marqdo mlsp`(`syntax` / `locate`)——不必背语法细节。
2. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
3. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
4. 可选:给函数/集合写**渐进式契约**(上节三种表格形状;写全或不写,别写一半)。
5. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
6. On errors:结构化诊断(含 `doc_anchor` / `suggestion`)→ `repair_targets` 取有界靶点,**只改锚点范围内**的行。
7. 提交前:`marqdo check path/to/file.mq.md`(或 `mlsp validate`)清到零 Error。
8. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
## Anti-patterns (common model mistakes)
@@ -339,8 +240,7 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Call `host_*` from `ext/linalg` | Use `la.*` L1 wrappers; plugin ABI only |
| Bare `kind=eig` inside `*…*` | `kind="eig"` — quote text literals |
| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` |
| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) |
@@ -357,5 +257,3 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
- [ ] 语法拿不准的地方已查 MLSP(`syntax`/`locate`),而不是凭记忆发明
- [ ] 契约(如有)与升参一致:`marqdo check` 零 Error
+50
View File
@@ -162,6 +162,56 @@ import browser:lib/browser.mq.md
Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md).
## 6e. Agent / LLM result maps — GFM first (positive)
Return and soft-error packs are **tables**, not `json.set` pipelines. Full style contract: [marqdo-dev](../marqdo-dev/SKILL.md) §2.
```markdown
---
import table:lib/table.mq.md
---
## step_ok
+ `task`
+ `reply`
`out` =
| status | task | result |
|--------|------|--------|
| ok | `task` | `reply` |
*out*
## step_err
+ `task`
+ `err`
`out` =
| status | task | error |
|--------|------|-------|
| error | `task` | `err` |
*out*
## soft_http_pack
+ `msg`
+ `usage0`
**empty_tc = > table.empty_list**
`pack` =
| finish | text | error | usage | tool_calls |
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
```
Do **not** mirror legacy `ext/ai/agent.mq.md` `json.parse`+`json.set` chains when adding new arms — convert the shape to a table.
## 7. Import text stdlib
```markdown
+16 -5
View File
@@ -126,16 +126,27 @@ jobs:
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **v1.5.0**:外联 v2 + 文档原生 Notebook——invoke/JSON call/并行/持久 Python·Node/状态桥 · cell 单步 · 高对比 view
- **v1.5.0**: Foreign v2 + document-native notebooks — invoke, JSON calls, fan-out, persistent Python/Node, state bridge, cell stepping, high-contrast view
- **v1.5.0 ext**:扩展包同步 1.5.0 / Ext pack 1.5.0
- **v1.4.6**:裸自增升参——首次粗体赋值左值即声明;`n = n + 1` 无反引号也是必选形参
- **v1.4.6**: Bare self-increment is a required parameter — first bold assignment LHS is a declaration
- **v1.4.5**:Streamable HTTP MCP + web invoke Bearer/401 · openai/agent json.get 硬化
- **v1.4.5**: Streamable HTTP MCP + web invoke Bearer/401; openai/agent json.get hardening
- **v1.4.2**:Agent/LLM 优化 O1–O5——sandbox trial · promote proof · step_route/EFI/cost · lint · quarantine
- **v1.4.2**: Agent/LLM optimize O1–O5 — sandbox trial, promote proof, step_route/EFI/cost, lint, quarantine
- **v1.4.1**:view 标注连线——SVG mid→mid(underline 底中 → chip 顶中)· 帧 chip id 对齐 · L→R 密度
- **v1.4.1**: View annot leaders — SVG mid→mid (mark bottom-center → chip top-center), frame chip id unify, L→R density
- **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参
- **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view
- **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源
- **v1.3.3**: Browse document-surface Structure — narration, markers, call/loop frames, `#mq-view-trace`, static site parity
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `reuse`/`find`/`duplicate` · Agent preflight(REUSE→ADAPT→CREATE)
- **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE)
- **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure`
- **v1.2.0**: Web Artifact (ADR 0007) — Document/Endpoint, web.serve/render/inspect, ext/data|security|net, compose_*/configure removed
- **v1.1.1**:AI 栈收口——llm `ask`/`stream`/`collect` · Metadata Binding · Skill Compilation + Adaptive Routing · MCP 客户端 + resume · 可选 `plugins/llm`
- **v1.1.1**: AI stack — llm ask/stream/collect, Metadata Binding, Skill Compilation + Adaptive Routing, MCP client + resume, optional plugins/llm
- **v1.0.7**:WS/网络边界加固;`url_encode` `%20`
- **v1.0.3**:Ubuntu PPA + 扩展 CDN(ext.marqdo.com)
- **Linux 包必出**:`*-native-x86_64-unknown-linux-gnu.zip` + Linux CLI bundle
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [mapping v0.3](https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping-v0.3.md)
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [ext-ai-optimize](https://github.com/cflmy/marqdo/blob/main/doc/roadmap/ext-ai-optimize.md)
### Downloads
+6
View File
@@ -87,3 +87,9 @@ tests/ext/:memory:
# local secrets
.env
# sandbox gold leftovers
tests/ext/_sbx_cow/
tests/ext/_sbx_*/
examples/**/_example_sbx/
+264
View File
@@ -8,6 +8,270 @@
### Changed
## v1.5.0 — 2026-10-18
### Highlights
**外联 v2 / 文档原生 Notebook**:`lib/foreign` 从“运行一段代码”升级为完整外联内核:结构化 `invoke` 记录、JSON 进出的 `call` / `call_many`、并行扇出、Python/Node 持久内核、显式状态桥,以及用绑定表声明的 Notebook 单元。`view` 增加 cell 单步、Run All、内核切换、journal、状态面板、浅/深主题与可调高度代码区;高对比度 token 修复了代码和 STRUCTURE 文字与背景区分度不足的问题。CLI · wasm · ext **1.5.0**。
```bash
git checkout v1.5.0 && cargo build --release
```
**核心表面 Δ(Core surface Δ)**:**无增删**——外联 v2 只扩展 `lib/foreign` 的库 API;Notebook 的 `内核表` / `会话表` 是既有绑定表;没有新增 Markdown 标记。
### Added
- **用户静态站(外联 / OKF / EKC)**:新增中英双语 `features/19-foreign-notebook` 与 `features/20-okf-ekc`,重写 `stdlib/foreign`,首页加入「一份文件三个面」、外联 Python 运行、Notebook 表、OKF/EKC 与 preflight 说明。
- **`lib/foreign` F0/F1**:`invoke` 结构化记录(`ok`/`code`/`stdout`/`stderr`/`ms`/`timed_out`/`truncated`/`result`);`run`/`run_lang` 新增 `env`/`cwd`/`timeout`/`args`/`max_output`;15 个语言预设;`probe`/`register`/`unset`/`load_config`;`.marqdo/foreign.toml`。
- **`lib/foreign` F2**:JSON 进 / JSON 出 `call`;并行 `run_many` / `call_many`(有序、单项隔离、并发上限);`invoke` 的 `input` / `output` / `result` / `result_error`。
- **`lib/foreign` F3/F3.5**:Python / Node 持久会话 `session_open` / `session_eval` / `session_close` / `session_list`;状态桥 `session_set` / `session_get` / `session_names`;会话超时即杀、崩溃隔离、drop 清理。
- **Notebook D1/D2**:`内核表` / `会话表` 文档原生语法;`DocumentSession`(cell index / 命名内核 / journal / value store);view Notebook 工具栏(Run All / Restart & Run All / Step / State / Journal / Reload)、状态徽标、内核下拉、Push/Pull 状态表单;`POST /api/session/*`。
- **Notebook D3**:`reload` 重新解析并保留内核,源码变更的 cell 标为 `dirty`;Journal/Reload/Debug 按钮;Debug 打开同一 view 服务的语句级单步页(`/debug` + `/api/debug/*`);状态桥 Push/Pull。
- **安全与健壮性**:所有外联入口检查 `exec` 能力;有界 stdout/stderr 读取与截断标记;stdin 写线程;Unix 进程组 / Windows `taskkill /T` 超时清理;shell-like argv 切分。
### Fixed
- **view 文档表面与标注 chip**:把旧 view 的 `--ink` / `--fill` / `--line` 等 token 映射到当前主题,修复 STRUCTURE 中 `main`、`内核表 =`、函数名和 annot-chip 深色文字/白色卡片与暗色背景不一致的问题。
- **view 代码对比度**:移除会互相覆盖的 highlight.js 深/浅两套外链样式,改用内置高对比 token 变量;深色代码正文 `#f0f0f0` on `#1e1e1e`(14.6:1),浅色 `#24292f` on `#f6f8fa`(13.8:1);关键词/字符串/注释均使用可读的对比色。
- **view 反向代理兼容**:Notebook / Debug 的 API 与 Debug URL 改为相对路径,可在 `/marqdo-view/...` 路径前缀下工作,便于 Docker 内通过 DSH 同源预览。
- **分支内共同局部变量**:if/else 各臂都赋值的局部变量不再被误提升为必选形参;修复 `# llm` 构造器无端要求 `key`,恢复 agent/llm/ext 全量测试。新增 `branch_else_common_local_is_not_a_param` 回归测试。
- **外联临时脚本路径**:入口目录为相对路径时,脚本参数现在使用绝对路径,避免 `tests/lib/tests/lib/...` 双拼接。
- **外联失败可观测**:解释器不存在时进入 `invoke` 记录,`run` 仍报错;view 显示 stderr / exit / ms。
### Changed
- **Notebook view 视觉重做**:采用 VS Code Dark 的扁平色板与 Jupyter 的 cell 组织:单一深色底、明确 surface/border 层级、`In [n]` / `Out [ ]` 提示、顶部 cell 工具栏、无渐变/无重阴影、暗色代码区与一致的字号/间距;保留并统一原始左侧文件导航、右侧 Functions/Variables 栏与 Execution/Source 区块;支持深色/浅色主题切换(localStorage 记忆)与代码区、输出区纵向拖拽调整高度。
- **`langs`** 现在返回「预设 ∪ 注册 ∪ 配置」的已知语言(原集合是子集)。
- 大输出从 `Err` 改为「截断 + `truncated=true`」;`subtask` 外联输出同步采用该语义。
## v1.4.6 — 2026-10-16
### Highlights
**裸自增升参**:粗体首次赋值的左值按设计 §8.2 视为声明。`**n = n + 1**` 在没有反引号提及时也会把 `n` 升成必选形参;缺参报 `missing argument for parameter`,不再是函数体内的 `undefined variable`。纯局部赋值(`**score = 1**`)与循环变量不升参。CLI · wasm **1.4.6**(扩展包仍为 **1.4.5**)。
```bash
git checkout v1.4.6 && cargo build --release
```
**核心表面 Δ(Core surface Δ)**:**无增删**——升参与 §8.2 对齐(赋值左值声明);不改 MQ 关键词 / 表几何。
### Fixed
- **升参**:`merge_inferred_params` 纳入首次粗体赋值左值。右值在绑定前读取同名(`n = n + 1`)时,该名成为必选推断形参。
### Changed
- CLI / wasm SemVer **1.4.6**。扩展包保持 **1.4.5**。
## v1.4.5 — 2026-10-16
### Highlights
**Streamable HTTP MCP + web `/v1` 鉴权硬化**:`agent_mcp_serve` 支持 `transport=http`(MCP Streamable HTTP 2025-03-26);web invoke 注入 `Authorization` / `X-Api-Key`,`ok=false`+`unauthorized` → HTTP 401;`ext/ai` openai/agent 字段访问改 `json.get`,消除 footnote 硬崩。CLI · Ext · wasm **1.4.5**。
```bash
git checkout v1.4.5 && cargo build --release
cargo build --release -p marqdo_plugin_agent
# HTTP MCP:
# QDAGENT_MCP_TRANSPORT=http marqdo run cli/求道-mcp.mq.md
marqdo ext add agent # CDN → 1.4.5
```
**核心表面 Δ(Core surface Δ)**:**新增** MCP Streamable HTTP 传输(`transport=http|streamable-http`);web invoke 契约扩展(header 注入 · 401);**无** MQ 关键词 / 表几何变更。
### Added
- **`agent_mcp_serve` Streamable HTTP**:`transport=http` · `host`/`port`/`path`;POST JSON-RPC + 可选 GET SSE;`Mcp-Session-Id`。facade:`ext/ai/agent` `## serve`。
### Fixed
- **web invoke**:`Authorization` / `X-Api-Key` 注入 payload;`jsonWrapInvokeValue` 对 `unauthorized` 返回 401;`{sse}` 自动 event-stream。
- **`ext/ai/llm/openai` · `agent` · `llm`**:字段访问改 `json.get` / `at`,避免 `[field](x)` 在非 map 上硬崩。
- **explore workbook**:子任务 `stream=False`(网关 SSE 524 更稳)。
### Changed
- CLI / Ext / wasm SemVer **1.4.5**。
- 设计:[doc/design/ext-web-artifact.md](doc/design/ext-web-artifact.md)(sse / bearer)。
## v1.4.4 — 2026-10-16
### Highlights
**LLM 传输软失败 + `ext/ai` 表优先重构**:上游连接拒绝/超时/HTTP≠200 时,Runtime 返回结构化 `finish|status=error`(不再硬中断 VM);`agent` / `智能体` / `llm/openai` 去掉 `json.set`/`json.append` 袋胶水。含 CLI host · `plugins/llm` · Ext pack **1.4.4**。
```bash
git checkout v1.4.4 && cargo build --release
cargo build --release -p marqdo_plugin_llm
marqdo run tests/ext/agent-llm-transport-soft.mq.md
marqdo ext add agent # CDN → 1.4.4
```
**核心表面 Δ(Core surface Δ)**:**无增删**——HTTP 宿主软失败契约 + Extension 风格重构;不改 MQ 关键词 / 表几何。
### Fixed
- **LLM / Agent 传输软失败**:`host_http_post` / SSE · `plugins/llm` · `ext/ai/llm/openai` 结构化 `finish=error`;`agent.step` / `plan` / `run` 收成 `status=error`。金样 `tests/ext/agent-llm-transport-soft.mq.md`。说明:[doc/research/agent-llm-transport-soft-2026-10.md](doc/research/agent-llm-transport-soft-2026-10.md)。
- **`agent.run`**:`cache == "soft-hit"` 引号比较(裸 `soft-hit` 曾被解析为减法)。
### Changed
- **`ext/ai` 去 json 胶水**:结果 map / 事件用 GFM 表 + `table.put` / `table.append` / `table.empty_*`。SKILL 正面示例:`.cursor/skills/marqdo-dev` §2 · `marqdo/examples.md` §6e。
- CLI / Ext / wasm SemVer **1.4.4**。
## Ext pack v1.4.3 — 2026-10-16
### Highlights
**Agent cold EFI / resolve 硬崩修复(CLI 仍为 v1.4.2)**:qdagent 接通 `agent.run` 时空 OKF 触发 `unknown function preflight` 与 `missing map key llm_free`。本包修复 `ext/ai/agent` facade 与 `agent` native;金样 `tests/ext/agent-run-cold-efi.mq.md`。说明:[`doc/research/agent-run-efi-resolve-bugs-2026-10.md`](doc/research/agent-run-efi-resolve-bugs-2026-10.md)。
```bash
marqdo ext add agent # CDN latest → 1.4.3
# 或:MARQDO_EXT_VERSION=1.4.3 marqdo ext add agent
```
**核心表面 Δ(Core surface Δ)**:**无增删**——仅 Extension / Agent Runtime 契约修补。
### Fixed
- **`agent.run`**:`efi=True` 改为 `` `self`.preflight ``(不再裸调全局 `preflight`)。
- **`agent_resolve` miss**:返回字段对齐命中路径,含 `llm_free: false`;facade 对 `llm_free` / route 字段改用 `json.get`。
### Changed
- 扩展包 SemVer **1.4.3**(`ext/VERSION`);与 CLI **v1.4.2** 可独立安装。
## v1.4.2 — 2026-10-16
### Highlights
**Agent/LLM 优化 O1–O5**:`ext/ai/sandbox` CoW 试跑接入 `agent.trial` / `run sandbox=`(默认关);promote 强制 sandbox proof;步骤路由 `step_route` + EFI preflight + `usage`/`token_cost`;风格 lint 与 `sandbox.report`;技能 `quarantine` 与离线 standing/policy 优化脚本。表优先、少 json 胶水。路线:[ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md)。
```bash
git checkout v1.4.2 && cargo build --release
cargo build --release -p marqdo_plugin_agent
marqdo run tests/ext/agent-sandbox-optin.mq.md
marqdo run examples/agent-sandbox-okf/index.mq.md
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add agent # CDN latest → 1.4.2
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Extension / Agent Runtime**(`ext/ai` 沙盒与晋升闸门),不触碰语言标记。
### Added
- **`ext/ai/sandbox`**:CoW 工作区(`open` / `run` / `diff` / `commit` / `discard` / `inspect` / `profile` / `report`);经 `plugins/agent` `sandbox_*` → `host_query`;默认拒 `plugin`/`exec`/`net`。
- **O1**:`agent.trial` · `run`/`step` `sandbox=` · 中文 `试跑`/`沙盒=` · 示例 `examples/agent-sandbox-okf/` · 金样 `agent-sandbox-optin`。
- **O2**:`agent_kb_promote` 默认 sandbox proof;OKF `applies_when`/`fixtures`/`sandbox_profile`/`proof`;harness Skill Lift。
- **O3**:`agent.step_route` · `ext/ai/policies/step-route.mq.md` · `run efi=`(缺工程知识时软放行)· 结果 `usage`/`token_cost`。
- **O4**:`scripts/mq-style-lint.sh` · `sandbox.report` markdown 审阅面。
- **O5**:`agent_kb_quarantine` / `agent.quarantine` · `scripts/optimize-standing-policy.sh`。
### Fixed
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.2**。
- Skill:强制表/链接取元、禁同文件混 EN/ZH、点名 sandbox 试跑习惯。
## v1.4.1 — 2026-10-15
### Highlights
**view 叙述标注连线**:Browse / `view output` 中 underline→chip 改为 SVG 正交连线(描述底边中点 → 轨道 → 短竖线 → 值顶边中点);同跨度多帧 chip 共用 annot id;可见 chip 按锚点 L→R;帧切换后重算密度。设计:[view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)。
```bash
git checkout v1.4.1 && cargo build --release
marqdo view public/00-welcome.mq.md --no-open
marqdo view output public -o /tmp/mq-public
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.4.1
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 标注几何与帧 chip 对齐),不触碰语言标记。
### Added
- 设计缺口文档 [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md):叙述 fence 卡、帧感知 chip 密度、L-leader 几何约定。
### Fixed
- view L-leader:id 与 mark 错配、chip 逆序交叉、border 无色变黑碎段、横线穿过 chip 文字;现为 mid→mid SVG path。
- 叙述 fence / 代码卡单层渲染;静态页隐藏 Run;主文函数引用 call chip + leader。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.1**。
## v1.4.0 — 2026-10-15
### Highlights
**叙述统一 + 公式 meta + 图片自写回**:块公式 `% marqdo: var=`;分支/循环体与函数体同权叙述;foreach 中英糖;自写回图片 `![marqdo-out](…)`(扩展名校验)与 view/静态站同源标记;view 展示推断形参实值;欢迎页迁到 v0.3 叙述面。
```bash
git checkout v1.4.0 && cargo build --release
marqdo run tests/markup-v03/formula-meta-var.mq.md
marqdo run tests/markup-v03/foreach-narrative.mq.md
marqdo view tests/view/document-annot-demo.mq.md --no-open
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.4.0
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。Language 层在既有 `formula` / `branch-list` / `loop-list` 上扩展语义(块公式 TeX 注释绑定、臂/循环体叙述、foreach 糖);Runtime:自写回图片形态 + view 推断形参展示。设计:[fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)。
### Added
- **块公式 meta 绑定**:`$$` 内 `% marqdo: var=<ident>`(剥离后解析;可无空 RHS);金样 `tests/markup-v03/formula-meta-var.mq.md`。
- **控制流叙述统一**:臂/循环体 `parse_indented_body` 与函数体同权;分支条件行支持叙述前缀与行内 `**…**`;foreach 糖 `- 对…的每一项…` / `- for each … in …`。
- **图片自写回**:路径/URL 且扩展名合法 → `![marqdo-out](…)`;文本仍 HTML 注释;view / `view output` 同源样式卡与 `<img>`。
- **view 推断形参实值**:Browse 展示 body-inferred 参数绑定值;欢迎页 EN/ZH 迁 v0.3 叙述。
### Fixed
- `ext/net/url.encode`:经 `lib/net` 包装,不再直接 `host_*`(金样 `ext_mq_md_never_calls_host`)。
- PPA 源包:`ppa-build-source.sh` 本地 `.orig` 已在 build-area 时跳过重复 `cp`。
- view:嵌套调用欢迎页与公式/代码卡渲染清理。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.4.0**;词法评论段遇有序分支臂 / 循环头 / 图片自写回标记时断开,避免吞掉控制流行。
## v1.3.3 — 2026-10-15
### Highlights
**view 文档面 Structure**:Browse 保真叙述与标记面(变量/语句/返回无源码定界符);表/循环/分支结构块;语句后绑定值、分支命中臂、函数多调用与循环迭代下拉(默认末帧);`#mq-view-trace` AI JSON。静态 `marqdo view output` 与 live view **同源渲染**(含用户站 `public/` → gh-pages)。
```bash
git checkout v1.3.3 && cargo build --release
marqdo view tests/view/document-annot-demo.mq.md --no-open
marqdo view output public -o public
# Ubuntu: sudo apt update && sudo apt install marqdo
marqdo ext add web # CDN latest → 1.3.3
```
**核心表面 Δ(Core surface Δ)**:**无增删**——19 个核心构造不变。本版为 **Runtime / Tooling**(view 文档面 + 帧选择),不触碰语言标记。
### Added
- **Browse Structure 文档面**(`src/view/document.rs` · `annot.rs`):叙述保真、标记面、GFM 表 / `doc-loop` / `doc-branch`、CSS L-leader 标注带。
- **StmtEvent / CallFrame / LoopFrame** 静默轨迹:post-stmt 绑定、分支 `call_id`、循环 `分 = 分数表[i] · value`;调用/迭代 picker(源码常显,只滤 chip)。
- **`ViewExecutionReport`** JSON(`#mq-view-trace` · `/api/view-trace` · SSE `trace_json`)。
- 设计:[view-document-annotations.md](doc/design/view-document-annotations.md) · [view-execution-trace.md](doc/design/view-execution-trace.md) · [view-frame-selection.md](doc/design/view-frame-selection.md);样例 `tests/view/document-annot-demo.mq.md`。
### Fixed
- 多调用分支 taken 混叠;调用切换误藏未执行臂源码;循环头重复 chip。
### Changed
- CLI / wasm / `ext/VERSION` **同步 1.3.3**;静态导出与 live view 共用 `build_file_view` → 文档面。
## Ext pack v1.3.2 — 2026-10-13
### Highlights
**Trailing slash 路由修复(CLI 仍为 v1.3.0)**:Go `ServeMux` 精确匹配导致 `/post/foo/`(带尾部斜杠)落入 404。新增 `withStripTrailingSlash` 中间件作为最外层 handler wrapper,所有下游中间件(RBAC、Tenant、路由)均看到规范化路径。覆盖静态路由、动态路由、根路径、查询参数保留。
```bash
marqdo ext add web # CDN latest → 1.3.2
# 或:MARQDO_EXT_VERSION=1.3.2 marqdo ext add web
```
### Fixed
- **web**: `/post/foo/` trailing slash now routes the same as `/post/foo` (dynamic and static routes). Root `/` unchanged. Query strings preserved after normalization.
## Ext pack v1.3.1 — 2026-10-08
### Highlights
Generated
+2 -2
View File
@@ -572,7 +572,7 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "1.3.0"
version = "1.5.0"
dependencies = [
"anyhow",
"assert_cmd",
@@ -603,7 +603,7 @@ dependencies = [
[[package]]
name = "marqdo-wasm"
version = "1.3.0"
version = "1.5.0"
dependencies = [
"marqdo",
"serde_json",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "1.3.0"
version = "1.5.0"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
@@ -19,7 +19,7 @@ cli = ["dep:clap"]
view = ["dep:tiny_http"]
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"]
plugin-host = ["dep:libloading"]
exec-host = []
exec-host = ["dep:libc"]
fs-host = []
tty = ["dep:libc"]
wasm-core = []
+15 -6
View File
@@ -149,15 +149,24 @@ marqdo catalog public -o .marqdo
---
## 现状(v1.3.0)
## 现状(v1.5.0)
- **外联 v2 / 文档原生 Notebook(v1.5.0)**:结构化 invoke · JSON call/call_many · 并行扇出 · Python/Node 持久内核 · 显式状态桥 · cell 单步/Run All/内核切换 · 高对比浅深主题;扩展包同步 **1.5.0**
- **裸自增升参(v1.4.6)**:首次粗体赋值左值即声明;`**n = n + 1**` 无反引号也升为必选形参。扩展包仍为 **1.4.5**
- **Streamable HTTP MCP + web invoke 鉴权(v1.4.5)**:`agent_mcp_serve transport=http` · Bearer/`X-Api-Key` 注入 · `unauthorized`→401 · openai/agent `json.get` 硬化
- **LLM 传输软失败 + `ext/ai` 表优先(v1.4.4)**:上游不可达 → `status=error`(不 abort);`agent`/`llm` 去 `json.set` 胶水 · [agent-llm-transport-soft-2026-10.md](doc/research/agent-llm-transport-soft-2026-10.md)
- **Ext pack 1.4.3**:修复 `agent.run` cold EFI(`` `self`.preflight `` + miss resolve `llm_free`);已并入 **≥1.4.4** · [agent-run-efi-resolve-bugs-2026-10.md](doc/research/agent-run-efi-resolve-bugs-2026-10.md)
- **Agent/LLM 优化 O1–O5(v1.4.2)**:`ext/ai/sandbox` CoW · `agent.trial` / `sandbox=` · promote sandbox proof · `step_route` / EFI / cost · style lint · quarantine · [ext-ai-optimize.md](doc/roadmap/ext-ai-optimize.md)
- **view 标注连线(v1.4.1)**:underline→chip SVG mid→mid(底边中点→轨道→短竖线→顶边中点)· 帧 chip 共用 id · L→R 密度 · [view-prose-annot-gaps.md](doc/design/view-prose-annot-gaps.md)
- **叙述统一 / 公式 meta / 图片自写回(v1.4.0)**:`% marqdo: var=` 块公式绑定 · 臂/循环体叙述与 foreach 中英糖 · `![marqdo-out](…)` 图片自写回 · view 推断形参实值 · [fence-meta-and-control-prose.md](doc/design/fence-meta-and-control-prose.md) · [stdlib-writeback.md](doc/design/stdlib-writeback.md)
- **view 文档面(v1.3.3)**:Browse Structure 叙述保真 · 标记面 · 分支/循环帧下拉 · AI `#mq-view-trace` · 静态 `view output` / gh-pages 同源 · [view-document-annotations.md](doc/design/view-document-annotations.md)
- **Engineering Knowledge(v1.3.0)**:EKC L0–L4 · `marqdo knowledge|find|reuse|duplicate|verify|…` · Agent `preflight` / REUSE→ADAPT→CREATE · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
- **Web Artifact(v1.2.0 · ADR 0007)**:Document/Endpoint 一等公民(`type: web|endpoint`)· facade `page`/`route`/`serve`/`render`/`inspect`/`use` · Resource 拆到 `ext/data`/`security`/`net` · 统一 View 表 · 破坏性移除 `compose_*`/`configure`
- **AI 栈(v1.1.1)**:`ext/ai/llm` 语义 `ask`/`stream`/`collect` · Artifact Metadata Binding(`${env|arg|sys|secret}`)· Agent Skill Compilation + Adaptive Routing · MCP stdio 客户端 + resume 检查点 · 可选 `plugins/llm` Transport ABI
- **AI 原生闭环(v1.1.0)**:核心表面守卫(19 构造,单边改动 CI 必红)· **渐进式契约**(文档内嵌 `参数`/`返回`/`字段` 表 + 四边界校验 + `marqdo check` 防漂移)· **MLSP for AI**(`marqdo mlsp`:`locate`/`syntax`/`validate`/`repair_targets`/`repair_apply`/`schema`,AI 按需查语法而非背诵)· **结构化诊断**(`run --json`,错误即数据);验证见 [perf-validation-report-2026-09-23.md](doc/roadmap/perf-validation-report-2026-09-23.md)
- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Variables 浮窗)
- **`marqdo view`**:文档浏览器(**文档面** Structure + 标注 / 调用·循环帧 + 函数大纲/搜索 + Execution + Variables 浮窗;`view output` 同构)
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页(默认挂钩 EKC)
- **`marqdo knowledge` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`**:Engineering Knowledge Compiler([engineering-knowledge.md](doc/design/engineering-knowledge.md))
@@ -167,7 +176,7 @@ marqdo catalog public -o .marqdo
- **`web`**:**Artifact 模型(ADR [0007](doc/adr/0007-web-document-endpoint.md))** — `type: web|endpoint` Document/Endpoint;facade `page`/`route`/`serve`/`render`/`inspect`/`use`;Resource 在 `ext/data` · `ext/security` · `ext/net`;设计 [ext-web-artifact.md](doc/design/ext-web-artifact.md);原生 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md));示例 [marqdo-blog](examples/marqdo-blog/) · [web-client-site](examples/web-client-site/) · [anlian-mq](examples/anlian-mq/)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
- **`linalg`**:L0–L6 + 公式文档面(中缀 / `declare` / 展示化简);示例 [linalg-transpose](examples/linalg-transpose/) · [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/)
- **`agent`**:A1–A4 + **MCP Server/Client stdio** + Skill Compilation + Adaptive Routing + resume + **Engineering preflight**(`agent.preflight` / `eng_preflight`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
- **`agent`**:A1–A4 + **MCP Server/Client**(stdio + **Streamable HTTP**)+ Skill Compilation + Adaptive Routing + resume + **Engineering preflight**(`agent.preflight` / `eng_preflight`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md) · [engineering-knowledge.md](doc/design/engineering-knowledge.md)
- **`llm`**:语义 `ask`/`stream`/`collect`(OpenAI/Ollama;可选原生 `plugins/llm`)
- 安装:`marqdo ext list` / `add …` / `remove`([ext-cli.md](doc/design/ext-cli.md);默认 `~/.marqdo/ext`)。原生插件先 `cargo build -p marqdo_plugin_*` 再 `ext add`
- **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum,linalg,llm}`(`web` 为 Go;其余为 Rust)
@@ -176,7 +185,7 @@ marqdo catalog public -o .marqdo
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
### 如何使用最新 Marqdo(v1.3.0)
### 如何使用最新 Marqdo(v1.5.0)
**安装解释器(任选其一)**
@@ -191,7 +200,7 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.3.0 # 或留在 main
git checkout v1.5.0 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -230,7 +239,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v1.3.0
# https://github.com/cflmy/marqdo/releases/tag/v1.5.0
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "1.3.0"
version = "1.5.0"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+53
View File
@@ -1,3 +1,56 @@
marqdo (1.4.6-1ppa1) noble; urgency=medium
* Marqdo 1.4.6: Promote a bare self-increment to a required parameter.
The first bold assignment LHS is a declaration (design §8.2); a missing
argument reports missing argument for parameter, not undefined variable.
-- cflmy <pingan@cflmy.cn> Fri, 16 Oct 2026 23:56:00 +0800
marqdo (1.4.5-1ppa1) noble; urgency=medium
* Marqdo 1.4.5: Streamable HTTP MCP (agent_mcp_serve transport=http);
web invoke Bearer/X-Api-Key inject + unauthorized→401; openai/agent
field access via json.get (no footnote hard-fail).
-- cflmy <pingan@cflmy.cn> Fri, 16 Oct 2026 17:40:00 +0800
marqdo (1.4.4-1ppa1) noble; urgency=medium
* Marqdo 1.4.4: Soft LLM transport errors (structured status=error);
ext/ai table-first refactor (no json.set glue).
-- cflmy <pingan@cflmy.cn> Fri, 16 Oct 2026 14:40:00 +0800
marqdo (1.4.2-1ppa1) noble; urgency=medium
* Marqdo 1.4.2: Agent/LLM optimize O1–O5 — sandbox trial opt-in,
promote sandbox proof, step_route/EFI/cost, style lint, quarantine.
-- cflmy <pingan@cflmy.cn> Fri, 16 Oct 2026 11:51:05 +0800
marqdo (1.4.1-1ppa1) noble; urgency=medium
* Marqdo 1.4.1: View annot leaders — SVG mid-to-mid (mark bottom-center
to chip top-center), unify frame chip ids, L-to-R chip density.
-- cflmy <pingan@cflmy.cn> Thu, 15 Oct 2026 20:40:00 +0800
marqdo (1.4.0-1ppa1) noble; urgency=medium
* Marqdo 1.4.0: Prose-unified control flow — block formula % marqdo: var=,
arm/loop narrative + foreach sugar, image writeback ![marqdo-out](...),
view inferred-param values; welcome pages on v0.3 prose surface.
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 15:53:00 +0800
marqdo (1.3.3-1ppa1) noble; urgency=medium
* Marqdo 1.3.3: Browse document-surface Structure — narration-preserving
markers, branch/loop frame pickers, ViewExecutionReport JSON; static
view output / gh-pages share the same render path as live view.
-- cflmy <pingan@cflmy.cn> Wed, 15 Oct 2026 13:20:00 +0800
marqdo (1.3.0-1ppa1) noble; urgency=medium
* Marqdo 1.3.0: Engineering Knowledge Compiler (EKC) — L0–L4 catalog,
+14 -2
View File
@@ -48,7 +48,13 @@
| [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** |
| [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** |
| [design/stdlib-math.md](design/stdlib-math.md) | **数学库(数值/随机/作图/轻量求解)** |
| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **外联胶水(\`\`\`lang 具名块)— 已落地** |
| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **外联胶水(\`\`\`lang 具名块)— v1 已落地** |
| [design/foreign-kernel.md](design/foreign-kernel.md) | **外联内核:持久内核 / JSON 桥 / 状态桥 / 安全** |
| [design/notebook-session.md](design/notebook-session.md) | **文档会话:cell / kernel / step / journal / 状态面板** |
| [design/notebook-syntax.md](design/notebook-syntax.md) | **文档原生 notebook 语法:内核表 / 会话表** |
| [research/foreign-notebook-decisions.md](research/foreign-notebook-decisions.md) | **外联 / notebook 决策记录(逐问逐答)** |
| [roadmap/foreign-v2.md](roadmap/foreign-v2.md) | **外联内核 v2 路线(F0–F4)** |
| [roadmap/notebook-session.md](roadmap/notebook-session.md) | **文档会话路线(D0–D5)** |
| [design/ext-abi.md](design/ext-abi.md) | **原生插件 C ABI v1**(`lib/plugin`) |
| [design/ext-llm.md](design/ext-llm.md) | **官方扩展 `ext/llm`(OpenAI 兼容)** |
| [design/ext-agent.md](design/ext-agent.md) | **官方扩展 `ext/agent`(文档驱动:单步 / 多步工作簿 + 自写回;废弃 thin TOOL 循环)** |
@@ -90,10 +96,16 @@
| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** |
| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** |
| [research/ai-agent-sandbox.md](research/ai-agent-sandbox.md) | **AI 扩展沙盒调研**:Wasm / OS / CoW / symlink 对比与 Marqdo 分层推荐 |
| [design/ext-ai-sandbox.md](design/ext-ai-sandbox.md) | **`ext/ai/sandbox` 设计锁定**:CoW · 能力表 · agent ABI(非 stdlib) |
| [roadmap/ext-ai-sandbox.md](roadmap/ext-ai-sandbox.md) | **`ext/ai/sandbox` 实现里程碑** S0–S4 |
| [research/ai-agent-llm-optimize-2026-10.md](research/ai-agent-llm-optimize-2026-10.md) | **2026-10 调研**:代码即文档×OKF×沙盒下的 Agent/LLM 优化与问题分析 |
| [design/ext-ai-optimize.md](design/ext-ai-optimize.md) | **Accepted**:Agent/LLM 优化 O1–O5 locked |
| [roadmap/ext-ai-optimize.md](roadmap/ext-ai-optimize.md) | **O1–O5 实现路线**(沙盒接入→证明晋升→路由/成本→lint→隔离) |
| [research/ext-hosting-gaps.md](research/ext-hosting-gaps.md) | **宿主集成缺口**:同域 SSE 中继 · HTTP→`##` · MCP Server · 副端口 · 跨模块 db/corpus |
| [design/ext-hosting-fill.md](design/ext-hosting-fill.md) | **宿主缺口补齐设计**(`ext/web` proxy/invoke · `ext/ai` mcp_server) |
| [roadmap/ext-hosting.md](roadmap/ext-hosting.md) | **宿主集成 H0–H4**(规划) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** · 后续优化见 [ext-ai-optimize](roadmap/ext-ai-optimize.md) O 波次 |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+142
View File
@@ -0,0 +1,142 @@
# 方案:智能体 / 大模型优化方向(代码即文档 · OKF · 沙盒)
| | |
|---|---|
| 状态 | **Accepted · O1–O5 locked** |
| 日期 | 2026-10-16 |
| 调研 | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) |
| 路线 | [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md) |
| 相关 | [ext-ai-sandbox.md](ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [okf.md](okf.md) · [engineering-knowledge.md](engineering-knowledge.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) · [ai-stack.md](../roadmap/ai-stack.md) |
---
## 0. 方案立场
1. **强化差异化**:可执行 `.mq.md` 为权威;OKF 为复用;沙盒为证明;LLM 为探索。
2. **不向隐藏 TOOL: 循环 / 向量权威回退。**
3. 下列方向均为**可行**;推荐波次见 §3,最终裁剪由你选型。
4. **不改** `doc/next/*`;落地时另开 roadmap 切片。
---
## 1. 架构愿景(闭环)
```text
目标 / 任务
│
▼
EFI / OKF lookup ──hit──► llm_free / marqdo 执行 ──► writeback
│ miss
▼
small-llm 路由 / 父分解
│
▼
生成或修补 .mq.md(代码即文档风格)
│
▼
sandbox.open → sandbox.run(caps)→ diff
│
├─ 失败 → writeback error / 隔离,不 promote
└─ 成功 → 人审或策略 → commit → solidify / OKF promote
│
▼
下次 REUSE(降本)
```
---
## 2. 可行方向全集
每个方向标注:解决的问题(Pn)、依赖、风险、粗粒度成本。
### A. 沙盒 × Agent 闭环
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **A1** | `step`/`plan` 默认经 sandbox 试跑再写实树 | P1 | 生成落 upper;绿才 `commit` | sandbox | 破坏现有金样默认 | 中 |
| **A2** | Promote / solidify 强制 sandbox proof | P1 | OKF 写入前要求 proof fixture 绿 | sandbox+OKF | 过严挡复用 | 中 |
| **A3** | Sandbox profile 表(caps 宣告) | P1/P3 | GFM 表声明 net/plugin/fs | sandbox | 表方言膨胀 | 低 |
| **A4** | Guest 风格门禁(表优先、禁 json 胶水) | P5 | commit 前 lint / preflight | sandbox+parser | 误杀合法 json.parse | 中 |
| **A5** | 会话 diff → view 审阅卡 | P1/P4 | HITL 看 CoW diff | view+sandbox | UI 工时 | 中高 |
| **A6** | 多会话并行 CoW(fan-out 实验) | — | 每假设一 session | sandbox | 隔离/合并复杂 | 高 |
### B. OKF / EKC / 技能层
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **B1** | OKF 技能元数据:适用条件 / fixtures / sandbox_profile | P2 | frontmatter + 目录约定 | okf | 与 catalog 字段冲突 | 中 |
| **B2** | Progressive disclosure(索引轻、正文按需 READ) | P2/P6 | 对齐 Anthropic Skills 层级 | agent A3 | 实现重复 | 中 |
| **B3** | Skill Lift 评测(有/无技能配对) | P4 | harness 指标 | B1 评测 | 样本少噪声大 | 中 |
| **B4** | 失败技能隔离(quarantine)+ 回归用例跟随血缘 | P1 | ForgeAgent 式 | OKF | 状态机复杂 | 中高 |
| **B5** | near-match / soft_match 产品化默认开 | P6 | 已有 roadmap | okf-near | 误复用 | 低中 |
| **B6** | EKC preflight 默认硬门槛(REUSE→ADAPT→CREATE) | P6 | step 前强制 EFI | EKC | 拖慢探索 | 中 |
| **B7** | Capability 包与 `llm_free` 资源双向链接 | P2 | catalog L3↔任务包 | EKC+OKF | 图维护 | 中 |
### C. 大模型 / 路由 / 成本
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **C1** | 步骤级路由(lookup / patch / sandbox_run / net) | P3 | 扩展 route policy 表 | routing | 策略过拟合 | 中 |
| **C2** | 总成本计量(含推理 token 膨胀)写回文档 | P7 | usage→writeback/metrics | llm result | 噪声 | 低中 |
| **C3** | 用强模型「反思」优化 standing / policy `.mq.md`(类 GEPA) | P3/P5 | 离线优化环,产物仍是文件 | llm | 需评测集 | 高 |
| **C4** | 高频 OKF 技能蒸馏/微调小模型(编译进权重) | — | 长期研究 | 数据+算力 | 运维重;偏离「源码权威」 | 很高 |
| **C5** | Named model 绑定任务类型(fast=路由,reasoning=分解) | P3 | 已有 named handles 加深 | llm | 配置漂移 | 低 |
| **C6** | Prompt document 强制:无参 ask 必须来自 type:prompt 文件 | P5 | 硬化 005 | llm | 破坏脚本式调用 | 低 |
### D. 代码即文档(产出质量)
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **D1** | 官方「可读 Marqdo」Skill 强化(表/链接取元/禁混名) | P5 | skills/marqdo 加厚 | skill | 模型仍违规 | 低 |
| **D2** | AST/结构 lint:json.set 链、混 EN/ZH API | P5 | `marqdo lint` 或 sandbox 钩子 | parser | 误报 | 中 |
| **D3** | 工作簿补丁只允许表驱动 / 命名槽写回 | P5 | 收紧 A0 补丁面 | agent | 表达力下降 | 中 |
| **D4** | 示例库:sandbox+OKF+表风格 canonical demos | P4/P5 | examples/ | 文档 | 维护 | 低 |
### E. 评测与产品化
| ID | 方向 | 解决 | 做什么 | 依赖 | 风险 | 成本 |
|----|------|------|--------|------|------|------|
| **E1** | 完成 Wave B1 harness(constitution / writeback / call_site) | P4 | 已规划 | agent | — | 中 |
| **E2** | 指标面板:ReuseRate / ProofRate / TokenCost | P4/P7 | metrics 写回或 catalog | agent | 虚荣指标 | 中 |
| **E3** | Live 金样矩阵(sandbox 开/关 × 路由后端) | P4 | CI optional | CI | flaky | 中 |
| **E4** | 教程:「只读一份 .mq.md 理解 Agent」 | — | doc/tutorial | 文档 | — | 低 |
### F. 明确不优先 / 需单独论证
| ID | 方向 | 理由 |
|----|------|------|
| **F1** | 第二套 Agent Framework(Python/TS 对象图权威) | 违宪 |
| **F2** | 向量库升为记忆权威 | 违宪;可作证据工具 |
| **F3** | 默认通用 shell Agent | 与 Marqdo-only 沙盒战略冲突 |
| **F4** | 整库 `ext/web` 进默认沙盒 | 已否决 |
| **F5** | 人人 microVM 本地默认 | DX 过重;留给 hosted |
---
## 3. 执行顺序(O1→O5 locked)
| 波次 | 方向组合 | 为何先做 |
|------|----------|----------|
| **O1** | A1 轻量(opt-in `sandbox=True`)+ A3 + D1 + D4 | 立刻接上刚落地的沙盒,风险可控 |
| **O2** | A2 + B1 + B3 + E1 | 验证→晋升→可度量 Skill Lift |
| **O3** | C1 + C2 + B6 | 降本与 EFI 硬门槛 |
| **O4** | A4 + D2 + A5 | 质量门禁与人审 |
| **O5** | B4 + C3 | 失败隔离与离线提示优化 |
| **O∞** | C4 / A6 | 研究项,单独立项 |
切片实现见 [ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。
---
## 4. 验收原则(任一波次)
- 金样:有/无沙盒、有/无 OKF hit、路由后端切换。
- 指标:至少报告 ReuseRate 或 TokenCost 之一相对基线变化。
- 文档:`.mq.md` 示例仍可读为 Markdown(表/链接取元,少 json 胶水)。
- 红线:不改 `doc/next/*`;ext 不调 `host_*`。
---
## 5. 落地
O1–O5 已锁定;实现见 [roadmap/ext-ai-optimize.md](../roadmap/ext-ai-optimize.md)。**仍不改** `doc/next/*`。
+104
View File
@@ -0,0 +1,104 @@
# Official AI sandbox (`ext/ai/sandbox`)
| | |
|---|---|
| Status | **Accepted · implementing** |
| Date | 2026-10-16 |
| Related | [research/ai-agent-sandbox.md](../research/ai-agent-sandbox.md) · [roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md) · [ext-agent.md](ext-agent.md) · [ext-abi.md](ext-abi.md) · [browser-marqdo-wasm.md](browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [stdlib-writeback.md](stdlib-writeback.md) |
---
## 0. One-liner
**Agent-only Marqdo trial runtime:** capability-isomorphic to browser Wasm defaults, CoW workspace until explicit `commit`, author surface under `ext/ai` (not stdlib).
---
## 1. Goals / non-goals
### Goals
| # | Goal |
|---|------|
| G1 | Open a CoW session over a workspace root; edits stay in upper until `commit` |
| G2 | `run` executes `.mq.md` (or in-memory source) under deny-by-default caps with core `lib/*` usable |
| G3 | `diff` / `discard` / `inspect` for review gates |
| G4 | Stable `unavailable in sandbox` for plugin.load, exec foreign/subtask path|code|lang, net (default), `ext/web` server APIs |
| G5 | Author API in `ext/ai/sandbox` via `plugins/agent` — **no** public `lib/sandbox` |
### Non-goals (this wave)
| # | Non-goal |
|---|----------|
| N1 | Embed wasmtime in CLI |
| N2 | True Wasm ABI plugins (linalg/quantum) |
| N3 | bwrap / microVM |
| N4 | Full `ext/web` listen/DB/WS inside sandbox |
| N5 | Symlink-forest workspace isolation |
| N6 | Default host-proxy of all native ABI plugins |
| N7 | Wire `agent.step`/`plan` through sandbox automatically (later) |
---
## 2. Layering
```text
ext/ai/sandbox.mq.md → plugin.load agent → sandbox_* ABI
↓ host_query
HostContext + CowSession
(fs / writeback see upper)
```
| Layer | May call `host_*` | Role |
|-------|-------------------|------|
| `ext/ai/sandbox` | **No** | Author facade |
| `plugins/agent` | via `host_query` only | Register `sandbox_*`; forward to host |
| `src/host` | — | CoW session store; fs/writeback intercept; nested `run` |
---
## 3. Author API
EN: `ext/ai/sandbox.mq.md` · ZH: `ext/ai/沙盒.mq.md` (separate files, no mixed names in one module).
| Method | Params | Result |
|--------|--------|--------|
| `open` | optional `root=` (default entry dir / cwd) | map `{ id, root }` |
| `write` | `id=`, `path=`, `text=` | none |
| `read` | `id=`, `path=` | text |
| `remove` | `id=`, `path=` | none (whiteout) |
| `diff` | `id=` | list of `{ path, kind: write\|remove }` |
| `commit` | `id=` | `{ ok, applied }` |
| `discard` | `id=` | `{ ok }` |
| `run` | `id=`, `path=` **or** `source=` | `{ ok, value, stdout?, error? }` |
| `inspect` | `id=` | caps, root, change count, notes |
Default `run` caps: `fs_write=true` (CoW only), `exec=false`, `net=false`, `plugin=false`.
---
## 4. CoW semantics
- **lower** = real workspace root (read-through).
- **upper** = session map path → bytes.
- **whiteout** = logical deletes; reads miss; commit unlinks lower.
- No symlink-as-isolation; resolve paths under root; reject `..` escape.
- Until `commit`, host tree unchanged (verifiable with `git status` / file mtime).
---
## 5. Hard bans
1. No public `lib/sandbox`.
2. No symlink forest as the isolation story.
3. No silent success when capability missing — diagnose `unavailable in sandbox`.
4. `ext/**` must not call `host_*`.
5. Do not treat empty `# main` as sandbox completeness.
---
## 6. ABI / host_query
Plugin exports (registered on agent plugin): `sandbox_open`, `sandbox_write`, `sandbox_read`, `sandbox_remove`, `sandbox_diff`, `sandbox_commit`, `sandbox_discard`, `sandbox_run`, `sandbox_inspect`.
Implementation: each forwards to allowlisted `host_query` names of the same stem (e.g. `sandbox_open`), which mutate the process-local CoW store and (for `run`) invoke nested capture with a sandboxed `HostContext`.
+2 -2
View File
@@ -120,8 +120,8 @@ import data:ext/data/db.mq.md
| `path` | `路径` | URL |
| `method` | `方法` | GET/POST/… |
| `request` | `请求` | `json` / `form` / `none` |
| `response` | `响应` | `json` / `text` / `html` |
| `auth` | `鉴权` | 角色名或 `none` |
| `response` | `响应` | `json` / `text` / `html` / `sse`(`text/event-stream`) |
| `auth` | `鉴权` | 角色名或 `none`;`bearer` / `api_key` = 不要求 cookie,把 `Authorization` / `X-Api-Key` 注入 payload 由 `# main` 校验 |
正文在请求时执行;返回值按 `response` 序列化。Result 协议见 §8。
@@ -0,0 +1,60 @@
# 块公式元数据绑定 · 控制流叙述统一
| | |
|---|---|
| 状态 | Active |
| 日期 | 2026-10-15 |
| 相关 | [stdlib-math.md](stdlib-math.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 块公式 `% marqdo: var=`
在 `$$…$$` 块内用 **TeX 行注释**声明绑定名(渲染通常不可见;运行时剥离后解析公式体):
```markdown
$$
% marqdo: var=f
x^2 - 2
$$
```
- 指令:`% marqdo:` + 空白 + `var=<ident>`;未知键 → Error。
- 可无前置 `` `f` = ``;若同时写空 RHS 与 `var=`,**同名允许、异名 Error**。
- **保留**旧空 RHS + 后随 `$$`。
- **不做**:行内 `$% marqdo:…$`;\`\`\` 代码围栏内语言注释 meta(本波)。
- 行内公式继续传统绑定:`` `g` = $x+1$ ``(单 `$…$` → `formula`)或 `` `g` = $$x+1$$ ``。
无名叙述区 `$$` 仍仅展示;可执行区裸块既无空 RHS 又无 `var=` → Error。
---
## 2. 臂 / 循环体叙述(与函数体同权)
`parse_indented_body` 与函数体相同:消费 `` `名` `` / `**代码**` / `*返回*`;纯叙述跳过。
斜体返回结束**当前臂或当前循环体**,不结束外层函数。
---
## 3. 循环头
| 面 | 写法 | 说明 |
|----|------|------|
| **推荐** | `- [项](xs)` / `- [`项`](`xs`)` | 支持嵌套 |
| 中文糖 | `- 对`xs`的每一项`项`` | 可选后缀「遍历」 |
| 英文糖 | `- for each `item` in `xs`` | 大小写不敏感 `for each` / `in` |
糖与链接头语义相同,可混用嵌套。
---
## 4. 分支条件行叙述
结构行仍以 `1.` / `2.` 开头。条件提取顺序:
1. 整段可解析为表达式(现状);
2. 行内粗体代码条件 `**`n` > 0**`;
3. 剥离「当/若/如果/when/if」与「时/则」后,将「大于/小于/等于…」映射为运算符再解析。
else:`N. *`(可夹「否则」等叙述,条件位仍为 `*`)。
禁止无标记自然语言整句当条件。
+449
View File
@@ -0,0 +1,449 @@
# 外联内核(Foreign Kernel)
| | |
|---|---|
| 状态 | **F0–F3.5 已实现** |
| 日期 | 2026-10-17 |
| 层 | Runtime(`src/foreign/` · `src/host/foreign*` · `lib/foreign.mq.md`) |
| 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-syntax.md](notebook-syntax.md) · [notebook-session.md](notebook-session.md) · [stdlib-foreign.md](stdlib-foreign.md) · [stdlib-subtask.md](stdlib-subtask.md) |
| 核心表面 Δ | 无 |
> 外联内核 = 一个长期存活的外部语言进程 + 生命周期 + 类型桥 + 记录。它既能被 `marqdo run` 里的显式调用使用,也能被 view 的 notebook 会话使用。
---
## 1. 定位与边界
### 1.1 负责
- 解释器发现、注册、配置、探测。
- 一次性执行:临时脚本、stdin/stdout/stderr、超时、输出上限。
- 持久内核:启动、求值、状态、关闭、列表。
- 状态桥:`session_set` / `session_get` / `session_names`。
- JSON 值桥:Marqdo `Value` ↔ JSON。
- 结构化记录:`ok/code/stdout/stderr/ms/timed_out/truncated/result/error`。
- 安全:`exec` 门禁、`cwd` 沙箱、进程组、并发/输出上限。
- 视图诊断:代码卡片 Run 的完整结果。
### 1.2 不负责
- 文档语法(`内核表` / `会话表`)→ [notebook-syntax.md](notebook-syntax.md)。
- 文档会话 / cell 顺序 / journal / view UI → [notebook-session.md](notebook-session.md)。
- Foreign → Marqdo 函数回调(v2 不做)。
- 依赖安装(pip/npm)。
- 远程 / 容器执行。
### 1.3 与相邻模块的区别
| 模块 | 生命周期 | 用途 |
|---|---|---|
| `foreign` | 一次性或持久 | 调外部语言;状态可选 |
| `subtask` | 一次性并发 | 后台任务、文件子任务、函数子任务 |
| `plugin` | 进程内 | 原生 C ABI 扩展 |
| `writeback` | 文档级 | 把输出写回 `.mq.md` |
`subtask` 不管理持久状态;`foreign` 不管理文档执行顺序。
---
## 1.4 实施状态(2026-10-17)
| 阶段 | 状态 | 关键文件 |
|---|---|---|
| F0 安全执行 / `invoke` 记录 | ✅ | `src/host/foreign.rs` |
| F1 预设 / probe / register / config | ✅ | `src/foreign/registry.rs` · `src/host/foreign.rs` |
| F2 JSON 桥 / run_many / call_many | ✅ | `src/host/foreign.rs` |
| F3 Python/Node 持久内核 | ✅ | `src/host/foreign_session.rs` |
| F3.5 session_set/get/names | ✅ | 同上 |
| F4 history / view 打磨 / 发布 | 部分 | — |
测试:`cargo test --lib foreign`(11+)、`cargo test --test gold lib_foreign`(12,python 条件跳过)、`tests/notebook/shared.mq.md` 手工 view 验证。
---
## 2. 语言与内核模型
### 2.1 语言预设
| lang | 别名 | 默认命令 | 扩展名 | 版本探测 | 会话 |
|---|---|---|---|---|---|
| `python` | `python3`, `py` | `python3`(Windows `python`) | `.py` | `--version` | ✅ |
| `node` | `javascript`, `js` | `node` | `.js` | `-v` | ✅ |
| `deno` | — | `deno run` | `.ts` | `--version` | ❌ |
| `bun` | — | `bun` | `.js` | `--version` | ❌ |
| `ruby` | — | `ruby` | `.rb` | `--version` | ❌ |
| `perl` | — | `perl` | `.pl` | `--version` | ❌ |
| `php` | — | `php -r {inline}` | `.php` | `--version` | ❌ |
| `lua` | — | `lua` | `.lua` | `-v` | ❌ |
| `r` | `rscript` | `Rscript` | `.R` | `--version` | ❌ |
| `julia` | — | `julia` | `.jl` | `--version` | ❌ |
| `go` | — | `go run {file}` | `.go` | `version` | ❌ |
| `bash` | `sh`, `shell` | `bash` | `.sh` | `--version` | ❌ |
| `powershell` | `pwsh`, `ps1` | `pwsh`(Windows `powershell`) | `.ps1` | `--version` | ❌ |
| `sqlite` | `sqlite3` | `sqlite3` | `.sql` | `--version` | ❌ |
| `tsx` | `typescript` | `tsx` | `.ts` | `--version` | ❌ |
说明:
- 预设只是默认值;注册 / 配置 / 环境变量整体覆盖。
- 会话能力首批只有 Python / Node;其它语言一次性执行。
- `php` 用 `{inline}`,围栏里直接写 PHP,不需要 `<?php`。
- `deno` 默认不给权限;需要时通过配置追加 `--allow-*`。
### 2.2 解析优先级
从高到低:
1. 调用级 `cmd`(整行 argv,shell-like 切分)+ `args`(追加)。
2. 进程内注册:`register` / `set_cmd`。
3. 环境变量 `MARQDO_FOREIGN_<LANG>`(整行或 JSON 数组)。
4. 项目配置 `.marqdo/foreign.toml` / `MARQDO_FOREIGN_CONFIG`。
5. 内置预设。
6. 都没有 → 带修复建议的诊断。
Python 额外发现顺序(在预设层内):
1. `VIRTUAL_ENV/bin/python`(Windows `Scripts/python.exe`);
2. `<cwd>/.venv` / `venv` / `env`;
3. 入口目录与 `fs_root` 向上查找;
4. PATH 的 `python3` / `python`。
`MARQDO_FOREIGN_NO_VENV=1` 关闭 venv 探测;显式 `cmd` / `set_cmd` / `MARQDO_FOREIGN_PYTHON` 优先。
相对路径:配置里的 `cmd` 相对配置目录;注册 / `set_cmd` / 环境变量里的 `cmd` 相对 `cwd`。
### 2.3 注册与模板
`register(lang, cmd?, args?, template?, ext?, env?, version_args?)`。
模板占位符:
| 占位符 | 展开 |
|---|---|
| `{file}` | 临时脚本绝对路径 |
| `{dir}` | 临时目录 |
| `{base}` | 脚本文件名 |
| `{inline}` | 源码作为一个 argv;不写临时文件 |
| `{lang}` | 语言 id |
| `{cwd}` | 实际工作目录 |
规则:
- `cmd` 与 `template` 至少一个;都给 → 报错。
- `{file}` 与 `{inline}` 不能同时出现。
- 都没有时自动追加 `{file}`。
- `{inline}` 超过 60 KiB → 报错并建议 `{file}`。
- 模板不做 shell 转义;需要 shell 时显式写 `bash -c`,路径由引擎生成(安全字符)。
配置示例:
```toml
[python]
cmd = ".venv/bin/python"
args = ["-u"]
[go]
template = ["go", "run", "{file}"]
[rust]
template = ["bash", "-c", "rustc -O {file} -o {dir}/main && {dir}/main"]
[php]
template = ["php", "-r", "{inline}"]
```
---
## 3. 一次性执行
### 3.1 API
| 英文 | 中文 | 形参 | 结果 |
|---|---|---|---|
| `run` | `运行` | `code`, 可选 `stdin` `env` `cwd` `timeout` `args` `max_output` | stdout 文本(v1 兼容) |
| `run_lang` | `按语言运行` | `lang`, `source`, 可选同上 | stdout 文本 |
| `invoke` | `执行` | 可选 `code` / `lang`+`source` / `stdin` / `input` / `env` / `cwd` / `timeout` / `args` / `output` / `max_output` / `cmd` / `keep` / `cache` | 记录 map |
| `call` | `调用` | 可选 `code` / `lang`+`source` / `input` / `stdin` / `env` / `cwd` / `timeout` / `args` | 解析后的 JSON 值 |
| `run_many` | `批量运行` | `runs`, 可选 `concurrency` | 记录列表 |
| `call_many` | `批量调用` | `inputs`, 可选 `code` / `lang`+`source` / `cmd` / `env` / `cwd` / `timeout` / `args` / `max_output` / `concurrency` | 结果值列表 |
### 3.2 记录结构
`invoke` / `run_many` / `session_eval` 共用:
| 键 | 类型 | 含义 |
|---|---|---|
| `ok` | Bool | exit=0 且未超时 |
| `code` | Int | 退出码;未启动 / kill → -1 |
| `stdout` | Text | 原始 stdout(可能截断) |
| `stderr` | Text | 原始 stderr(可能截断) |
| `ms` | Int | 墙钟毫秒 |
| `lang` | Text | 实际语言 |
| `cmd` | Text | 实际 argv |
| `timed_out` | Bool | 是否超时 |
| `truncated` | Bool | stdout/stderr 是否截断 |
| `result` | 任意 / None | 按 `output` 解析 |
| `result_error` | Text | json 解析失败原因 |
| `error` | Text | 启动 / 超时 / 策略原因 |
| `script` | Text | `keep=True` 的脚本路径 |
| `cached` | Bool | 缓存命中(P4) |
`session_eval` 额外:`id`、`alive`。
### 3.3 输出模式
| `output=` | `result` |
|---|---|
| `auto`(默认) | 尝试 JSON;失败 → None |
| `text` | None |
| `json` | 解析;失败 → `result_error` |
| `lines` | 行列表 |
| `bytes` | stdout 原始字节的 base64 |
`call` 固定 JSON:空 stdout → None;非空非法 JSON → 错误。
### 3.4 失败语义
- `run` / `call`:执行失败 → `Err`;错误包含语言、argv、退出码、stderr(截 4 KiB)、stdout 头。
- `invoke` / `run_many`:执行失败 → 记录;只有参数非法 / 策略拒绝 → `Err`。
- 输出过大:截断 + `truncated=true`,不再 OOM / 报错。
---
## 4. JSON 状态桥
### 4.1 值映射
| Marqdo | JSON |
|---|---|
| None | null |
| Bool | bool |
| Int | number |
| Num | number(NaN/Inf → null) |
| Text | string |
| List | array |
| Map | object |
| Formula | 矩阵 → 二维数组;其它 → 数字或字符串 |
| Code | 源码字符串 |
| Secret | JSON 中 `<secret>`;`env` 显式交付时取真实值 |
### 4.2 输入
- `input=` → JSON;写 stdin;同时提供 `MARQDO_INPUT`(≤8 KiB)与 `MARQDO_INPUT_FILE`(任意大小)。
- `stdin=` 文本与 `input=` 互斥。
- 都不给 → stdin EOF。
- 大输入走文件,避免环境变量大小限制。
### 4.3 输出
- `result` 按 `output` 解析。
- 原始 stdout/stderr 始终保留(截断到上限)。
- `call` 返回解析值;`invoke` 返回记录。
### 4.4 类型限制
v2 是**值拷贝**,不是对象引用:
- Python DataFrame / NumPy / Node 对象 → 需要先 `to_dict` / `to_json` / `JSON.stringify`。
- 大对象传输成本高;后续考虑 Arrow / Parquet / 文件句柄。
- Secret 不默认进入 JSON;需要 env 显式交付。
---
## 5. 持久内核与会话
### 5.1 API
| 英文 | 中文 | 形参 | 结果 |
|---|---|---|---|
| `session_open` | `会话开启` | `lang`, 可选 `cmd` `env` `cwd` `timeout` | 会话 id(Text) |
| `session_eval` | `会话求值` | `id`, 可选 `code` / `source` / `input` / `timeout` | 记录(含 id/alive) |
| `session_set` | `会话设值` | `id`, `name`, `value` | None |
| `session_get` | `会话取值` | `id`, `name` | JSON 值 / None |
| `session_names` | `会话变量` | `id` | 名称列表 |
| `session_close` | `会话关闭` | `id` | Bool |
| `session_list` | `会话表` | — | map 列表 |
### 5.2 支持语言
| 语言 | 方式 |
|---|---|
| python | `python3 -u -c <bootstrap>` |
| node | `node -e <bootstrap>` |
| 其它 | 报错:`lang=… has no session bootstrap; use run/invoke` |
### 5.3 线路协议
stdin 每行一个 JSON 请求;原始 stdout 每行一个 JSON 响应:
```json
{"id":1,"code":"x = 41","input":null}
{"id":2,"code":"x + 1","input":null}
```
```json
{"id":1,"ok":true,"stdout":"","stderr":"","result":null,"error":""}
{"id":2,"ok":true,"stdout":"","stderr":"","result":42,"error":""}
```
- 同一会话严格串行:等到匹配响应后才发下一条。
- 响应单行;JSON 转义换行。
- 崩溃 / EOF → `alive=false`,会话移除。
- 超时 → kill 会话(状态不可信)。
### 5.4 Python bootstrap
- 保留原始 `sys.stdout` 写协议;用户输出用 `redirect_stdout/stderr` 捕获。
- `ast.parse`:最后一条是表达式 → 先 exec 前面,再 eval 最后,作为 result。
- 异常 → `traceback.format_exc(limit=8)`,`ok=false`;会话继续。
- `input` → 全局 `marqdo_input`。
- 不可序列化 → `default=str`。
### 5.5 Node bootstrap
- 保存原始 `process.stdout.write` 写协议。
- eval 期间替换 `console.*` 与 `process.stdout/stderr.write`;结束后恢复。
- `vm.runInThisContext` 保留全局状态;`require` 挂到 `globalThis`。
- Promise → await;顶层 await 需用户包 `(async()=>{…})()`。
- 序列化失败 → `String(result)`。
### 5.6 状态桥
- `session_set`:值 → JSON → 请求 `{"set": name, "value": ...}` 或执行一段赋值。
- `session_get`:请求 `{"get": name}` → JSON → Marqdo Value。
- `session_names`:请求变量名列表。
- 与 `session_eval` 同一线路协议;严格串行。
- 名称必须是合法标识符;保留名(`marqdo_input` 等)另行文档。
### 5.7 生命周期
- id 为 `s1`、`s2`…。
- 每会话独立进程、cwd、env。
- `HostContext` drop → 全部 kill + wait。
- `subtask` 不继承会话。
- 不跨文档共享。
---
## 6. 环境契约
| 变量 | 值 |
|---|---|
| `MARQDO_FOREIGN` | `1` |
| `MARQDO_FOREIGN_LANG` | 语言 id |
| `MARQDO_FOREIGN_SCRIPT` | 脚本路径(文件模式) |
| `MARQDO_FOREIGN_DIR` | 脚本目录 |
| `MARQDO_FOREIGN_CWD` | 实际 cwd |
| `MARQDO_ENTRY` | 入口 `.mq.md` 路径 |
| `MARQDO_ENTRY_DIR` | 入口目录 |
| `MARQDO_INPUT` | input JSON(≤8 KiB) |
| `MARQDO_INPUT_FILE` | input JSON 文件(任意大小) |
语言默认:
- Python:`PYTHONUNBUFFERED=1`、`PYTHONIOENCODING=utf-8`、`PYTHONUTF8=1`;`PYTHONPATH` 前插 cwd。
- Node:`NODE_PATH` 前插 cwd(可选)。
`env` 是 map;值 `as_display()`;Secret 取真实值(显式交付)。不主动清空父环境。
---
## 7. 临时文件与 cwd
- 默认 `<cwd>/.marqdo/tmp/foreign-<pid>-<nanos>/`;不可写 → 系统临时目录。
- `MARQDO_FOREIGN_TMPDIR` 覆盖。
- 脚本 `main.<ext>`;Python 加 utf-8 声明。
- 默认 cwd = 入口目录;调用级 cwd 经 `resolve_path` + `fs_root` 校验。
- 成功/失败/超时都清理;`keep=True` 保留并回填 `script`。
- Node 相对 `require('./x')` 相对脚本目录;需要项目相对路径时用 `MARQDO_FOREIGN_CWD` 或 `{inline}` 模板。
---
## 8. 超时、IO、进程组
- `timeout`:秒,可小数;默认 10s;上限 3600s;`<=0` 报错。
- 超时 kill 进程组:
- Unix:`process_group(0)` + `kill(-pid, SIGKILL)`;
- Windows:`taskkill /PID <pid> /T /F`。
- `max_output`:每流默认 1 MiB;范围 1 KiB–64 MiB;保留前 N 字节,余下丢弃并继续排空;`truncated=true`。
- stdin 独立写线程,避免双向管道死锁;EPIPE 忽略。
- stdout/stderr 两个读线程;UTF-8 lossy。
- 记录原始字节(至上限)以支持 `bytes` 输出。
---
## 9. 安全
| 项 | 策略 |
|---|---|
| 能力门禁 | `run` / `invoke` / `probe` / `session_*` 全部检查 `allow_exec()`;沙箱 → 拒绝 |
| shell | 默认不经 shell;模板显式 `bash -c` 才走 |
| cwd | `resolve_path` + `fs_root`;越界拒绝 |
| 输出 | 有界读取 + 丢弃式排空 |
| 时间 | 上限 + 进程组 kill |
| 并发 | 默认 4,上限 32 |
| 会话 | 每文档独立;关闭/drop 清理;超时即杀 |
| Secret | JSON 不默认暴露;env 显式;面板打码 |
| wasm | `exec-host` 关闭时全部返回清晰错误;`langs` 返回 [] |
---
## 10. 兼容性
- `run` / `run_lang` / `set_cmd` / `langs` 既有调用可用。
- `run` 成功仍返回 stdout(去一个尾换行);非 0 仍报错。
- `set_cmd` 增加可选 `args`。
- `langs` 扩展为「预设 ∪ 注册 ∪ 配置」;原集合是子集。
- `subtask` 的 `spawn code=` / `lang=` 仍返回 stdout 文本。
- HostFn id 只追加;字节码参数 < 255。
- 无核心表面 Δ。
---
## 11. 测试矩阵
| 测试 | 依赖 | 断言 |
|---|---|---|
| 既有 `foreign-python` / `run-lang` / `外联-python` | python | 兼容 |
| `foreign-invoke` | node | ok/code/stdout/stderr/ms |
| `foreign-env-cwd` | node | env/cwd/MARQDO_* |
| `foreign-timeout` | node | timed_out, 无遗留进程 |
| `foreign-call-json` | node | 嵌套 list/map 往返 |
| `foreign-call-many` / `run-many` | node | 顺序/隔离/并发 |
| `foreign-session` | node(python 可选) | 跨 eval 状态、异常不杀 |
| `foreign-session-set-get` | node | 变量推拉 |
| `foreign-session-timeout` | node | alive=false |
| `foreign-probe` | node | path/version/ok |
| `foreign-register` | node | 模板 `{inline}` |
| `foreign-config` | node | `MARQDO_FOREIGN_CONFIG` |
| `foreign-caps` | 无 | exec=false 拒绝 |
| 单元测试 | 无 | shell 切分/模板/别名/JSON |
当前环境无 Python:node + bash 为主;python 条件跳过;Windows 用 `python_available()` / `bash_available()` 守卫。
---
## 12. 实现落点
| 文件 | 内容 |
|---|---|
| `src/foreign/registry.rs` | 预设/别名/模板/venv/PATH/配置/shell 切分(纯逻辑) |
| `src/host/foreign.rs` | Job/Execution/ForeignEnv;run/invoke/call/run_many/call_many;probe/register/unset/langs/load_config |
| `src/host/foreign_session.rs` | Python/Node bootstrap;会话生命周期;set/get/names |
| `src/host/dispatch.rs` | HostFn 追加 |
| `src/aliases.rs` | 参数别名 |
| `lib/foreign.mq.md` / `lib/外联.mq.md` | L1 API + 文档 |
| `src/view/mod.rs` / `html.rs` / `debug_page.rs` | Run 诊断;后续接文档会话 |
| `tests/gold.rs` / `tests/lib/foreign-*.mq.md` | 测试 |
---
## 13. 明确不做
- Foreign line-level step。
- Foreign → Marqdo 函数 callback。
- 自动镜像变量。
- 跨语言共享对象引用。
- 全进程快照。
- 自动安装依赖。
- 浏览器 wasm 外联。
+3 -1
View File
@@ -215,7 +215,9 @@ v0.3:
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
| ` ```lang ` | 外联(不变) |
| ` ```lang ` | 外联(不变;绑定仍用 `` `名` = `` + 围栏) |
| `$$` 内 `% marqdo: var=名` | 块公式绑定([fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)) |
| `- 对`集`的每一项`项`` / `for each` | foreach 叙述糖;推荐 `- [项](集)` |
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
+530
View File
@@ -0,0 +1,530 @@
# 文档会话(Document Session)
| | |
|---|---|
| 状态 | **D1–D3 首版已实现;D4/D5 待做** |
| 日期 | 2026-10-17 |
| 层 | Runtime + Document(view 服务端 / notebook 交互) |
| 相关 | [notebook-syntax.md](notebook-syntax.md) · [foreign-kernel.md](foreign-kernel.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [view.md](view.md) · [view-debug.md](view-debug.md) · [stdlib-subtask.md](stdlib-subtask.md) |
| 核心表面 Δ | 无(读取既有 AST 与表格) |
> 文档会话是 view 背后的“notebook 运行时”:它记住哪些 cell、在哪个内核、按什么顺序执行、状态是什么、结果是否过期。
---
## 1. 目标
1. **像 Jupyter 一样即时**:点一个 cell 就执行,状态保留。
2. **不像 Jupyter 一样隐藏**:执行顺序、内核归属、状态、过期情况都可查。
3. **不破坏 Marqdo 程序语义**:`marqdo run` 仍是规范执行;view 会话是交互镜头。
4. **Git 友好**:状态/输出不默认写进 `.mq.md`。
5. **多语言**:命名内核 + 显式状态桥。
6. **可复现**:Run All / journal / dirty / stale / replay。
---
## 1.1 实施状态(2026-10-17)
| 能力 | 状态 | 位置 |
|---|---|---|
| `内核表` / `会话表` 解析(中英列名) | ✅ | `src/notebook/mod.rs` |
| cell index(绑定名 / 行号 / source hash) | ✅ | 同上 |
| 命名内核 + 默认内核 + 语言校验 | ✅ | 同上 |
| 同内核共享 / 跨内核隔离 | ✅ | Node 金样例 + 单测 |
| `run_cell` / `step` / `run_all(restart)` | ✅ | `DocumentSession` |
| `restart_kernel` / `assign_kernel` | ✅ | 同上 |
| `kernel/interrupt` | 待做 | — |
| 状态桥 `push` / `pull` / `state_list` | ✅ | `DocumentSession` + `foreign_session` |
| journal(记录 + API + Journal 按钮) | ✅ | `DocumentSession::journal_json` · view |
| view 工具栏 / 状态徽标 / 内核下拉 / 状态表单 | ✅ | `src/view/html.rs` |
| `POST /api/session/*` | ✅(含 `reload`) | `src/view/notebook_api.rs` |
| cell step | ✅ | 同上 |
| Marqdo statement step | ✅(notebook 工具栏 Debug → 同一 view 服务的 `/debug`;`/api/debug/*`) | `src/debug` · `src/view/debug_api.rs` |
| dirty/stale 自动检测 | 部分(reload → dirty;assign → dirty;stale 传播待做) | `src/notebook/mod.rs` |
| writeback 集成 | 待做 | `writeback` |
| replay / 持久化 | 待做 | — |
| Python 会话 | ✅(本机无 python,CI/用户机条件测试) | `src/host/foreign_session.rs` |
| Node 会话 | ✅ | 同上 |
首版刻意不做:把状态写进 `.mq.md`、自动镜像变量、foreign 行级 debug、跨文档共享内核。
---
## 2. 两种执行模式
### 2.1 Program mode(规范)
- 入口:`marqdo run doc.mq.md` / CI / `view` 的 `Run document`。
- 执行:`# main` 程序语义;外联通过显式 `foreign.session_open/eval/call` 编排。
- 状态:一次运行内有效;运行结束进程退出(除非显式持久内核)。
- 结果:可复现;是文档的“真理”。
### 2.2 Notebook mode(交互)
- 入口:`marqdo view doc.mq.md` → Session 面板。
- 执行:按 `会话表`(或自动顺序)逐 cell 执行。
- 状态:内核持久;可切换、重启、单步。
- 结果:默认临时显示;可显式 writeback。
- 不是“真理”:是探索界面;需要复现时用 Run All 或把编排写进 `# main`。
### 2.3 两者关系
```text
.mq.md
/ \
Program mode Notebook mode
(canonical) (interactive)
\ /
Document Session
├── cell index
├── kernel registry
├── journal
└── state panel
```
- 共享 cell index 与 kernel registry。
- Program mode 可以不使用 notebook 表;Notebook mode 可以使用。
- 冲突时以 Program mode 为准;Notebook mode 不改变文档语义。
---
## 3. 文档会话模型
```text
DocumentSession
├── doc_path / doc_hash
├── cells: Vec<Cell>
│ ├── id (name / anon@line)
│ ├── name (binding)
│ ├── lang
│ ├── line_start / line_end
│ ├── source_hash
│ ├── kernel (resolved)
│ └── status: never | clean | dirty | stale | error | running
├── kernels: KernelRegistry
│ ├── name → ForeignSession
│ └── default per language
├── value_store: HashMap<String, Value> // Marqdo 侧会话值
├── journal: Vec<ExecutionRecord>
├── created_ms / last_active_ms
└── mode: program | notebook
```
### 3.1 Cell
- 只有**绑定名**的代码围栏才是 cell:
```markdown
`加载` =
```python
...
```
```
- 未绑定围栏仍是叙述,不是 cell。
- `id`:优先绑定名;匿名围栏用 `anon@<line>`(不进入会话表)。
- 同名 cell 重复 → 诊断;会话表按名字引用。
- `source_hash` 用于 dirty 判断。
- `line_start/line_end` 用于定位;编辑后重建索引。
### 3.2 Cell index 构建
1. 读取/解析文档(现有 `parse_source` / `load_module`)。
2. 遍历 AST,找 `Stmt::Assign { name, value: Expr::Code(c) }`。
3. 记录 name、lang、source、span、source hash。
4. 读取 `内核表` / `会话表` 绑定(见 [notebook-syntax.md](notebook-syntax.md))。
5. 解析 kernel 声明与 cell 归属;校验;生成诊断。
6. 生成执行顺序:
- 有会话表 → 行顺序;
- 无 → 文档顺序。
7. 未入会话的 cell → 状态 `unlisted`,UI 显示徽标。
### 3.3 Kernel registry
- key:`<document_id>:<kernel_name>`。
- 默认:`default:python`、`default:node`,按需启动。
- 命名:来自 `内核表`,首次执行时启动。
- 状态:`idle | starting | ready | busy | dead`。
- 同一 kernel 的 cell 严格串行;不同 kernel 可并行。
- 重启:kill + 清空状态 + 重新启动;cell 状态变 `never`。
- 关闭:kill + 移除。
### 3.4 Value store(Marqdo 侧会话值)
- 保存可从 Marqdo 推入内核的值(来自最近一次 Program run 的 bindings,或用户手动输入)。
- 也保存从内核取回的值(`session_get` / 状态面板 Pull)。
- 不是解释器 Env 的实时镜像;它是会话层的**值缓存**。
- 注入解释器:未来通过 `SessionEnv` 或显式变量赋值;v2 不做隐式注入。
- 用途:
- 状态面板显示;
- Push 到内核;
- 作为 `session_set` 的值来源;
- journal 记录。
### 3.5 Journal
每次执行追加一条:
```json
{
"seq": 3,
"cell": "汇总",
"kernel": "分析",
"lang": "python",
"ok": true,
"code": 0,
"ms": 42,
"source_hash": "…",
"stdout_hash": "…",
"result_hash": "…",
"started_ms": 1760000000000,
"error": ""
}
```
用途:
- 执行序号 / 顺序;
- dirty/stale 判断;
- replay;
- 视图显示;
- 调试(“为什么这个 cell 有值”)。
存储:内存 + 可选 `.marqdo/sessions/<doc-hash>.json`(默认 git 忽略)。
---
## 4. 执行语义
### 4.1 操作
| 操作 | 语义 |
|---|---|
| **Run cell** | 执行选中的 cell;必要时启动/复用 kernel |
| **Run above** | 按会话顺序执行到选中 cell(含) |
| **Run all** | 按会话顺序执行全部;可选 `restart` |
| **Step next cell** | 执行会话顺序中的下一个未执行/选中 cell |
| **Step next statement** | Marqdo 语句级单步(DebugController) |
| **Restart kernel** | kill + 重建;cell 状态 `never` |
| **Interrupt** | kill 当前 cell 进程组;kernel 标记 dead 或重启 |
| **Reset session** | 关闭所有 kernel,清 journal / value store |
### 4.2 执行一个 cell
```text
resolve cell -> resolve kernel
-> ensure kernel ready
-> [送入?] 显式 bridge 由文档代码/UI 负责
-> foreign.session_eval(kernel, source, input?)
-> record -> update cell status
-> [取回?] 由文档代码/UI 负责
-> journal append
-> view update
```
- 默认 cwd = 文档目录;env = kernel env。
- 输出:stdout / stderr / result / ms / truncated。
- 失败:cell 状态 `error`;journal 记录;不自动重试。
- 同一 kernel 串行;UI 禁用并发 Run。
### 4.3 Step 语义
| 类型 | 行为 |
|---|---|
| **Cell step** | 执行下一个会话 cell;状态保留 |
| **Marqdo statement step** | 执行下一条 Marqdo 语句;遇到 `foreign.session_eval` 时整个外联调用原子完成 |
| **Foreign line step** | 不做;未来 DAP |
- Cell step 是 Notebook mode 的主单步。
- Statement step 复用 `DebugController`;需要把 debug session 与 DocumentSession 关联。
- 两者可以互相切换:cell step 到某个 Marqdo cell 后可 statement step;语句执行完回到 cell 边界。
### 4.4 中断
- `Interrupt`:向当前 kernel 进程组发 SIGINT/SIGKILL;记录 `interrupted`。
- 若 kernel 状态不确定 → 标记 dead;建议 restart。
- 不允许“中断后继续用同一 kernel”除非确认状态。
### 4.5 并发
- 同一 kernel:一次一个 cell。
- 不同 kernel:可并行(例如 Python 分析与 Node 前端)。
- `Run all` 默认按会话顺序串行;可配置“按 kernel 并行、按依赖串行”(后续)。
- 并发上限沿用 foreign(32)。
---
## 5. 状态桥(会话层)
### 5.1 显式 API
文档代码:
```markdown
把 `数值表` 送进 `分析` 内核:
**> foreign.session_set id="分析" name="xs" value=`数值表`**
从 `分析` 内核取回 `mean`:
**`均值` = > foreign.session_get id="分析" name="mean"**
```
### 5.2 状态面板
- 左侧:Marqdo 侧值(最近 Program run bindings + value store)。
- 右侧:每个 kernel 的变量(`session_names` + 按需 `session_get`)。
- 操作:
- Push:选 Marqdo 值 → kernel 变量;
- Pull:选 kernel 变量 → value store / 显示;
- Refresh;
- 复制名称/值。
- Secret 打码;大对象显示摘要(类型/长度/repr 截断)。
### 5.3 自动镜像
- v2 不做。
- 后续 `mirror`:`mq_` 前缀、白名单、按值拷贝、默认关。
- 原因见 [decisions](../research/foreign-notebook-decisions.md) §1-F。
### 5.4 类型
- JSON 拷贝;复杂对象需 `to_dict` / JSON。
- 大对象:v2 显示摘要;传输用文件/DB。
- 未来:Arrow / Parquet / 共享文件句柄。
---
## 6. Dirty / Stale / Run All
### 6.1 定义
| 状态 | 条件 |
|---|---|
| `never` | 未执行 |
| `clean` | 上次执行成功后源码未变 |
| `dirty` | 源码 hash 变了 |
| `stale` | 上游 cell 变了(依赖图;v2 先按会话顺序近似) |
| `error` | 上次执行失败 |
| `running` | 正在执行 |
| `unlisted` | 不在会话表 |
### 6.2 依赖
- v2:会话表行顺序 + 简单规则:
- 若上游 cell 的 source_hash 变了,下游标 `stale`;
- 若 kernel 重启,全部 `never`。
- v2.1:变量级依赖图(静态分析 + bridge 表),精确 stale。
- 不假装 Jupyter 的“隐藏顺序”:顺序就是表/文档顺序。
### 6.3 Run All
- 默认:按会话顺序执行;可选 `restart=true`。
- 规范执行:**restart + run all**;UI 明确按钮 `Restart & Run All`。
- 未重启时:显示“当前 kernel 有历史状态”警告。
- 执行后:生成 session summary(ok/fail/耗时/跳过的 cell)。
### 6.4 Replay
- 用 journal 的顺序和输入 hash,在新 kernel 上重放;
- 比较 stdout/result hash;
- 输出 divergence 报告。
- v2 可选;至少保留 journal 以便未来实现。
---
## 7. 输出与文档
### 7.1 默认
- Notebook mode 输出只在 view 中显示;不写 `.mq.md`。
- 关闭/刷新后可通过 journal 恢复最近结果(若 session 持久化)。
- 不写 execution_count 到文档。
### 7.2 显式 writeback
- 复用 `lib/writeback` 的 `<!-- marqdo-out … -->`。
- cell 输出锚点:cell 名 + 行号;写入位置在围栏之后,或文档末尾的“输出”区。
- 可选:
- 单 cell 写回;
- 全部写回;
- 只写回文本/数值,不写复杂对象。
- Git 友好:输出是普通 Markdown 注释块;可 diff、可忽略。
### 7.3 不写回
- 避免 Jupyter 的 `.ipynb` 输出噪声。
- 需要分享结果时,导出 HTML / 静态 view,而不是改源文件。
---
## 8. View 交互
### 8.1 工具栏
```text
[Run All] [Restart & Run All] [Step Cell] [Step Statement]
Kernel: [分析 ▾] Status: ready [Restart] [Interrupt]
[State] [Journal] [Writeback ▾]
```
### 8.2 每个 code card
```text
`加载` python · kernel 分析 · run #3 · 42ms · clean
[Run] [Step] [Kernel ▾] [State] [Copy output]
```
- 状态徽标:`never` / `clean` / `dirty` / `stale` / `error` / `running` / `unlisted`。
- 输出区:stdout / stderr / result / 截断提示。
- 内核下拉:切换归属;不迁移状态;提示需要重跑。
- `Step` = 执行此 cell(cell step)。
### 8.3 状态面板
- Marqdo / kernel 分栏。
- Push/Pull。
- Secret 打码。
- 大对象摘要 + 复制 JSON。
### 8.4 Journal 面板
- 表格:seq / cell / kernel / ok / ms / 时间 / 错误。
- 点击跳转 cell。
- 导出 JSON。
### 8.5 键盘
- `Ctrl/Cmd + Enter`:Run cell。
- `Shift + Enter`:Run cell + 下一个。
- `Alt + Enter`:Run cell + 插入?不做。
- `F10`:Step statement(与 debug 一致)。
- `F5`:Run All。
---
## 9. 服务端 API
所有 API 以文档相对路径 + session id 定位;session 内存驻留,进程退出即失。
| 方法 | 路径 | 作用 |
|---|---|---|
| POST | `/api/session/open` | 打开文档会话,返回 cells / kernels / journal |
| POST | `/api/session/close` | 关闭会话,kill 所有 kernel |
| POST | `/api/session/reload` | 重新解析文档,保留 kernel(标记 dirty) |
| POST | `/api/session/cell/run` | 执行指定 cell |
| POST | `/api/session/cell/step` | 执行下一个 cell |
| POST | `/api/session/run_all` | 按会话顺序执行;`restart` 可选 |
| POST | `/api/session/kernel/restart` | 重启指定 kernel |
| POST | `/api/session/kernel/interrupt` | 中断当前 cell |
| POST | `/api/session/kernel/assign` | 改 cell 的 kernel 归属(会话内) |
| POST | `/api/session/state/list` | Marqdo / kernel 变量列表 |
| POST | `/api/session/state/push` | Marqdo 值 → kernel |
| POST | `/api/session/state/pull` | kernel 变量 → value store |
| POST | `/api/debug/*` + `/debug` | Marqdo 语句单步(Debug 按钮,复用 debugger) |
| POST | `/api/session/writeback` | 显式写回 cell 输出 |
| POST | `/api/session/journal` | 执行日志 |
| GET | `/api/session` | 当前会话摘要 |
响应统一:`{ok, session, ...}`;错误 `{ok:false, error, code?}`。
---
## 10. 生命周期与持久化
- Session key:`<root>/<doc_rel>`;每个文档一个。
- 打开:解析、建 cell index、按需启动 kernel。
- 空闲超时:默认 30 分钟关闭(可配置)。
- 文档关闭 / 服务退出:kill 所有 kernel。
- 文件变更:view 刷新时 `reload`;cell hash 变化 → dirty;kernel 保留。
- 持久化(可选):
- `.marqdo/sessions/<doc-hash>.json`:kernel 名称/语言、cell 归属、journal、value store 摘要;
- 默认 git 忽略;
- 不持久化进程状态 / 大对象。
- 不把 session 状态写进 `.mq.md`。
---
## 11. 安全
| 项 | 策略 |
|---|---|
| exec | 所有 kernel 启动/执行检查 `allow_exec`;沙箱拒绝 |
| 生命周期 | 每文档;关闭/drop kill;不跨文档 |
| cwd | 文档目录 / `fs_root`;越界拒绝 |
| 输出 | 有界;截断标记 |
| 超时 | cell 级;进程组 kill |
| 中断 | 杀进程组;kernel 标记 dead |
| Secret | 状态面板打码;JSON 不默认暴露 |
| 未信任文档 | 不自动打开会话;必须显式 Run |
| 并发 | 同 kernel 串行;不同 kernel 上限 32 |
| writeback | 显式;路径沙箱;不自动改文档 |
---
## 12. 测试
### 12.1 服务端
- cell index:绑定名/行号/lang/source hash;未绑定围栏排除。
- 表解析:内核表/会话表/自动模式/重复/未知/语言不匹配。
- 会话:open/close/reload;kernel 启动/重启/中断。
- cell run:状态机 never→running→clean/error;dirty/stale。
- step:cell step 顺序;statement step 与 debug 联动。
- state:push/pull/list;Secret 打码;大对象摘要。
- journal:顺序、hash、失败。
- 并发:同 kernel 串行;不同 kernel 并行。
- 安全:exec=false 拒绝;cwd 越界;超时。
### 12.2 金样例
- `tests/notebook/kernels.mq.md`:内核表/会话表。
- `tests/notebook/shared-state.mq.md`:两个 Python cell 共享 `x`。
- `tests/notebook/step.mq.md`:cell step 顺序。
- `tests/notebook/state-bridge.mq.md`:Marqdo ↔ Python 推拉。
- `tests/notebook/invalid-*.mq.md`:诊断。
- 依赖:node 为主,python 条件跳过。
### 12.3 UI
- 手工冒烟:Run cell / Step / Run All / Restart / State Push/Pull / Journal。
- 不引入前端测试框架;用服务端 API + 静态检查。
---
## 13. 与 Jupyter 对照
| 维度 | Jupyter | Document Session |
|---|---|---|
| 源 | `.ipynb` | `.mq.md` |
| 执行顺序 | 隐藏的 `In[n]` | 会话表 / 文档顺序 / journal |
| 状态 | 隐藏 kernel | kernel + value store + 状态面板 |
| 多语言 | 一 notebook 一 kernel | 命名内核 + 每 cell 归属 |
| 单步 | cell | cell + statement |
| 复现 | 手动 | Restart & Run All + journal + replay |
| Git | 输出/计数噪声 | 源码干净;输出显式 |
| 知识 | 无 | OKF / catalog |
| 调试 | 语言 pdb | Marqdo 断点 + cell 级;行级后续 |
---
## 14. 实现顺序(D 层)
| 阶段 | 内容 |
|---|---|
| D0 | 设计/语法/决策文档(本文件) |
| D1 | `src/notebook/`:cell index、表解析、session 结构、诊断 |
| D2 | 服务端 API:open/close/cell run/step/run_all/restart/interrupt |
| D3 | view UI:工具栏、cell 徽标、kernel 下拉、状态面板、journal |
| D4 | statement step 接入;dirty/stale;writeback |
| D5 | replay / 持久化 / 并发优化 / 测试补全 |
依赖 F 层:F3 持久内核、F3.5 状态桥先完成,D2 才能工作。
---
## 15. 明确不做(v2)
- Foreign line-level step。
- 自动镜像变量。
- 跨文档共享 kernel。
- 全进程快照。
- 自动执行 cell。
- 把 session 状态写进 `.mq.md`。
- 前端 SPA 框架重写;沿用现有 HTML/JS。
+305
View File
@@ -0,0 +1,305 @@
# 文档原生 Notebook 语法
| | |
|---|---|
| 状态 | **Decided;D1 解析已实现** |
| 日期 | 2026-10-17 |
| 层 | Document(读取约定) + Runtime(校验) |
| 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-session.md](notebook-session.md) · [foreign-kernel.md](foreign-kernel.md) · [core-surface.md](core-surface.md) · [layers.md](layers.md) |
| 核心表面 Δ | **无**——不新增标记;只用既有 `# main` / 赋值 / 表格 / 反引号 |
> 目标:让“这段代码在哪个内核里、按什么顺序执行、和谁共享状态”像目录一样可读,而不是像 IDE 配置一样可读。
---
## 1. 为什么不用围栏元数据
Jupyter 的 cell 元数据、VS Code 的 `kernel=`、YAML 的 `kernels:` 都属于**代码/编辑器思维**:
- 读者看到的是一行属性,不是一段知识;
- 属性藏在围栏 info string 或 JSON 里,Markdown 预览看不见意图;
- 一旦加 `kernel=`,它就是 Language 层语法,需要 ADR、core-surface 增行;
- 同一个文档的执行计划被拆散到每个围栏,无法一眼总览。
Marqdo 的选择:
> **执行计划本身是一张表。表是文档的一部分,人先读表,机器再读表。**
这不是新语法。GFM 表已经是集合,`` `名` = `` + 表已经是数据绑定;我们只约定两个**数据表的名字**。
---
## 2. 两个约定数据表
它们放在 `# main`(或唯一入口对象)的体内,和代码单元并列:
```markdown
# main
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | 读取与清洗数据 |
| 绘图 | python | | 独立环境 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 加载 | 分析 | 读取原始数据 |
| 清洗 | 分析 | 处理缺失值 |
| 汇总 | 分析 | 按城市聚合 |
| 绘图 | 绘图 | 输出 SVG |
```
为什么是“绑定的表”,不是 `# 外联内核` 对象:
- `#` 是对象/函数;把元数据做成顶层对象会把文档拆成多个作用域,code fence 会被困在对象里。
- 绑定表是入口体内的**数据**,与 cell 同一作用域;不执行、不改变控制流。
- View / 文档会话读取 AST 中的绑定值,不需要执行文档。
- 解析器零改动。
### 2.1 `内核表` / `kernels`
| 列 | 必填 | 含义 |
|---|---|---|
| `名称` / `Name` | ✅ | 内核名,供 `会话表` 引用;建议用领域词(分析/绘图/前端) |
| `语言` / `Language` | ✅ | 预设 id 或已注册语言:`python` / `node` / … |
| `命令` / `Command` | 可选 | 覆盖解释器命令;空白 = 预设 / `set_cmd` / 配置 / 环境变量 |
| `说明` / `Notes` | 可选 | 给人读的一句话;不影响执行 |
规则:
- 名称在文件内唯一;重复 → 诊断。
- 语言不支持会话时,内核仍可声明,但只能执行一次性 cell;`session_*` 报错。
- `命令` 只写可执行文件;参数请用 `.marqdo/foreign.toml` 或 `session_open`。
- 没有 `内核表`:每种语言自动一个 `default` 内核。
- 声明了内核但 `会话表` 没引用:允许,只是没有被使用。
### 2.2 `会话表` / `session`
| 列 | 必填 | 含义 |
|---|---|---|
| `单元` / `Cell` | ✅ | 代码围栏的绑定名(`` `加载` = `` 后面的名字),表格里**不写反引号** |
| `内核` / `Kernel` | ✅ | `内核表` 中的名称,或语言 id(`python` / `node`)表示该语言默认内核 |
| `说明` / `Notes` | 可选 | 给人读的一句话 |
规则:
- **行顺序 = 执行顺序**。这是 `Run All`、`Step`、`Run Above` 的规范顺序。
- 只有列出的 cell 参与会话;未列出的代码围栏仍然显示,但标记为“未入会话”,Run All 不执行。
- 没有 `会话表`:所有绑定名的代码围栏按**文档出现顺序**自动入会话,每种语言用默认内核。
- `单元` 必须对应一个已绑定名的代码围栏;找不到 → 诊断。
- 同名 cell 重复出现 → 诊断;建议一个名字只绑一个围栏。
- `内核` 未声明且不是语言 id → 诊断,列出已声明内核。
- cell 的语言与内核语言不一致 → 诊断;别名等价(`python3`/`py` ↔ `python`)。
- 表可以出现在 `# main` 体内任意位置;读者可以从表一眼看到执行计划。
### 2.3 为什么放在 `# main` 体内
- `# main` 是入口;cell 绑定与元数据表同一作用域。
- `marqdo run` 会正常求值这两个表(得到 `List of Map`),没有副作用。
- 文档会话从 AST / 最近一次运行的 bindings 读取它们;不需要新的解析路径。
- 如果文档没有 `# main` 而是唯一 `#` 对象,同样适用。
---
## 3. 完整示例
````markdown
# main
这份文档演示一个最小 notebook:两个 Python 单元共享 `分析` 内核,
一个绘图单元在隔离的 `绘图` 内核里运行。
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | 数据读取与聚合 |
| 绘图 | python | | 独立绘图环境 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 加载 | 分析 | 读取原始数据 |
| 清洗 | 分析 | 处理缺失值 |
| 汇总 | 分析 | 按城市聚合 |
| 绘图 | 绘图 | 输出 SVG |
`加载` =
```python
import json
rows = [
{"city": "上海", "value": 3},
{"city": "北京", "value": 5},
]
print(json.dumps(rows, ensure_ascii=False))
```
`清洗` =
```python
rows = [r for r in rows if r["value"] > 0]
```
`汇总` =
```python
from collections import Counter
counts = Counter(r["city"] for r in rows)
print(dict(counts))
```
`绘图` =
```python
print("plot-ready")
```
`汇总` 和 `绘图` 分属两个内核;`绘图` 看不到 `rows`。
需要共享时,用 Marqdo 显式把值送过去:
**> foreign.session_set id="绘图" name="rows" value=`rows`**
````
读者即使不运行,也能从 `会话表` 读出:先加载、再清洗、再汇总,最后绘图;前三个共享 `分析`,绘图在 `绘图`。
---
## 4. 自动模式(没有表)
### 4.1 没有任何约定表
````markdown
# main
`分析` =
```python
x = 41
```
`结论` =
```python
print(x + 1)
```
````
解释:
- 两个 cell 都是 `python`;
- 自动使用 `default:python` 内核(一个);
- 按文档顺序执行;
- 共享 `x`。
现有文档不需要改一行就能在 view 里 cell-by-cell 运行。
### 4.2 只有内核表
- 所有 cell 按文档顺序;
- 每种语言解析到该语言的 `default` 内核;
- 命名内核只有被 `会话表` 引用时才使用。
### 4.3 只有会话表
- `内核` 列只能写语言 id;
- 每个语言 id 解析到该语言默认内核;
- 未列出的 cell 不入会话。
---
## 5. 可读性规则(语法评审标准)
新增/修改任何 notebook 语法,必须满足:
1. **先读人话**:去掉执行语义后,表格仍像目录/清单。
2. **不使用属性串**:不写 `kernel=…`、`class=…`、JSON/YAML 元数据。
3. **不隐藏意图**:执行顺序、内核归属必须在一处可见。
4. **不引入新标记**:只用 `#` / 表格 / 反引号 / 既有代码面。
5. **默认安全**:表格只声明,不自动执行;只有 Run / Step 触发。
6. **命名用领域词**:`分析`、`绘图`、`前端`,不用 `k1`、`default`、`stage2`(除非确实是默认)。
7. **说明列可选但推荐**:给未来的读者/LLM 一点上下文。
8. **错误可读**:诊断要指出“哪个单元、哪个内核、哪一行、怎么修”。
9. **中英对称**:中文用中文列名,英文用英文列名;语义一一对应。
10. **无表也能跑**:约定表是增强,不是前置条件。
---
## 6. 诊断规范
| 情况 | 诊断(中文示例) | 修复建议 |
|---|---|---|
| 内核名重复 | `内核表: 内核名「分析」重复(第 12、20 行)` | 改名或合并 |
| 会话引用未知内核 | `会话表: 单元「汇总」引用了未声明的内核「分析」` | 在 `内核表` 声明,或改用语言 id |
| 会话引用未知单元 | `会话表: 找不到名为「清洗」的代码单元` | 检查 `` `清洗` = `` 绑定 |
| 单元重复 | `会话表: 单元「汇总」重复出现` | 每个单元只列一次 |
| 语言不匹配 | `会话表: 单元「前端」(node) 不能使用 python 内核「分析」` | 换内核或换语言 |
| 未入会话 | (非错误)view 徽标:`未入会话` | 需要时加一行 |
| 内核表为空 | `内核表: 至少声明一个内核,或删除该表使用默认内核` | 删除表或补行 |
| 会话表为空 | `会话表: 至少列出一个单元,或删除该表使用自动顺序` | 删除表或补行 |
原则:**不静默忽略**。读者必须知道为什么某个 cell 没跑。
---
## 7. 与 Program mode 的关系
- `内核表` / `会话表` 是**声明**,不是执行指令。
- `marqdo run` 仍然执行 `# main` 的程序语义;这两个表会被求值为普通数据。
- Program mode 的外联编排用显式 API(`foreign.session_open` / `session_eval` / `call`);表只服务 view 的 notebook 会话与一键 Run All。
- 两种模式可以并存:
- 文档用表描述“交互时怎么跑”;
- `# main` 用显式调用描述“CI 时怎么跑”。
- 如果两者冲突,以 Program mode 的程序语义为准;Notebook mode 的表只影响 view。
这样避免把“执行计划”变成第二套程序语义。
---
## 8. 状态桥的语法边界
v2 **不**为状态交换新增表格/注释。原因:
- “什么时候送、什么时候取、送到哪个内核、赋值给哪个 Marqdo 变量”需要精确语义;
- 若做成隐式表格动作,容易产生隐藏状态与顺序歧义;
- v2 先用显式 API,把时序讲清楚:
```markdown
把 `数值表` 送进 `分析` 内核:
**> foreign.session_set id="分析" name="xs" value=`数值表`**
从 `分析` 内核取回 `mean`:
**`均值` = > foreign.session_get id="分析" name="mean"**
```
- view 提供状态面板与 Push/Pull 按钮,减少手写 API 的需要;
- 声明式 `共享表` 作为 v2.1 提案,等 session value store 与“每次单元执行前后”的时序稳定后再引入。
这不是降级:v2 的功能完整(可读可写、可推可拉),只是不用隐式语法承载时序。
---
## 9. 未来扩展(不承诺进 v2)
1. `共享表`:
`| 内核变量 | Marqdo 变量 | 方向 | 说明 |`,每次单元执行前送入、后取回。
2. 每个 cell 的“运行条件/依赖”列:`依赖` 列声明上游单元。
3. 内核别名:`内核表` 的 `名称` 可被 `use` 或短名引用。
4. 多文件会话:跨 `.mq.md` 的共享内核(默认仍隔离)。
5. 语言特定的“会话能力”列(是否支持持久、是否支持行级调试)。
任何一项都要先过 §5 的可读性规则与 `core-surface` 检查。
---
## 10. 实现落点
| 逻辑 | 位置 |
|---|---|
| 识别 `内核表` / `会话表` 绑定 | `src/notebook/syntax.rs`(新) |
| 读取绑定值 | AST `Stmt::Assign` + `Expr::Table` / `Expr::List`;或最近一次 run 的 bindings |
| 校验名称/语言/重复/未入会话 | 同上;错误进入现有 Diagnostic |
| cell index(绑定名/行号/语言/source hash) | 解析后的 `Module` 遍历 |
| 只读展示 | view Structure:表渲染成普通表格 + 徽标 |
| 执行 | Document Session API(见 [notebook-session.md](notebook-session.md)) |
解析器本身**不需要改**。这是本设计最重要的约束:语法是既有标记的组合,不是新构造。
+18 -2
View File
@@ -314,10 +314,15 @@ type: Marqdo Agent Skill
title: <短名>
sig: <12hex>
resource: ../../resources/<slug>.mq.md
status: stable | candidate
status: stable | candidate | quarantine
llm_free: true | false
quality: <int>
hits: <int>
# O2 optional metadata (from workbook frontmatter; see §7.5):
applies_when: <text condition or tag>
fixtures: <relative .mq.md proof path>
sandbox_profile: default | readonly | <name>
proof: <relative .mq.md> # alias of fixtures for sandbox gate
generated:
by: marqdo-agent/plan
at: <ISO8601>
@@ -331,7 +336,7 @@ verified:
Prefer spawning `resource` over re-planning.
```
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。**O2:** `agent_kb_promote` 默认要求 sandbox proof(`proof` / `fixtures` / workbook 本身经 `sandbox.run` 成功)才写入;失败返回 `promoted: false` / `reason: sandbox_proof_failed`。传 `require_proof=false` 仅用于明确豁免。
### 7.3 任务签名 → Concept 路径
@@ -401,6 +406,17 @@ Prefer spawning `resource` over re-planning.
| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` |
| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 |
| 分发 | 整包 `agent-kb/` 可复制(格式即契约) |
| **证明晋升(O2)** | `applies_when` / `fixtures` / `sandbox_profile` / `proof` 写在技能与 workbook frontmatter;promote 前 `sandbox.run` 绿才 `llm_free` |
| **隔离(O5)** | 失败技能 `status: quarantine`;回归 fixture 跟随 slug |
### 7.5a 技能 frontmatter 约定(O2 B1)
| 字段 | 含义 |
|------|------|
| `applies_when` | 适用条件(短文本 / 标签);路由与 harness 可读 |
| `fixtures` | 相对路径:sandbox 证明用 `.mq.md` |
| `sandbox_profile` | `default` / `readonly` / 其它 `sandbox.profile` 名 |
| `proof` | 与 `fixtures` 同义;promote 优先读 `proof` 再 `fixtures`,否则跑 workbook 自身 |
---
+2 -2
View File
@@ -2,9 +2,9 @@
| | |
|---|---|
| 状态 | **已落地(v1)** |
| 状态 | **v1 已落地**;v2 设计见 [foreign-kernel.md](foreign-kernel.md) · [notebook-session.md](notebook-session.md) · [notebook-syntax.md](notebook-syntax.md) |
| 日期 | 2026-08-06 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-math.md](stdlib-math.md)(公式同构绑定) |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-math.md](stdlib-math.md)(公式同构绑定) · [foreign-kernel.md](foreign-kernel.md) · [notebook-session.md](notebook-session.md) · [roadmap/foreign-v2.md](../roadmap/foreign-v2.md) |
---
+14 -4
View File
@@ -34,7 +34,16 @@
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
**推荐(块内元数据)**:在 `$$` 体内用 TeX 注释声明变量(见 [fence-meta-and-control-prose.md](fence-meta-and-control-prose.md)):
````markdown
$$
% marqdo: var=f
sin(x) + x
$$
````
**兼容**:空 RHS 赋值后跟展示数学块(与 `` `xs` = `` 后跟表格一致):
````markdown
# main
@@ -52,13 +61,14 @@ $$
也支持:
- 单行围栏:下一行 `$$x^2 - 2$$`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`(历史面)
- 行内:`` `g` = $x+1$ `` 或 `` `g` = $$x+1$$ ``
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区裸 `$$` 若既无空 RHS 又无 `% marqdo: var=` → 报错。
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
**行内 `$…$`:** 传统绑定 `` `名` = $…$ `` → `formula`;**不**使用 `$% marqdo:…$`(会破坏 Markdown/TeX 识别)。
### 2.3 从文本构造
+22 -5
View File
@@ -8,9 +8,11 @@
## 定位
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` → `marqdo view`(及静态 `view output`)在对应语句下显示 **output-card**,并在源码面用 **writeback** 样式标出块本身。
## 存储格式
## 存储格式(两种,可并存)
### 1. HTML 注释(文本 / 结构化输出)
```markdown
*`n` = > len value=`xs` *
@@ -30,11 +32,26 @@ pending
-->
```
- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
### 2. Markdown 图片(生成图 / 审计友好)
当 `value` **看起来像图片引用**(扩展名 `.png` / `.jpg` / `.jpeg` / `.gif` / `.webp` / `.svg` / …,或 `data:image/…`)时,`record` **自动**写成:
```markdown
![marqdo-out](plots/out.svg)
![marqdo-out ok](plots/ok.png)
```
- 普通 Markdown 预览即可看见图;view / 静态站额外加 writeback 标记与 output-card 中的 `<img>`。
- 非图片路径仍走注释块;把非图片硬写成 `![marqdo-out](…)` 时扫描会忽略(校验失败)。
- `list` / `scan_path` 结果带 `kind`: `comment` | `image`。
### 共用规则
- 标记字为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
- 默认在**调用行下方**插入或替换紧邻**无键**块
- `at_end=true`:替换文件末尾的**无键**块
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽;`ensure` 在缺失时写入占位且不覆盖已有正文
- `line=` / `行=`:显式锚点行号;主机侧有全局互斥锁
### 替换跨度与空行
+1 -1
View File
@@ -4,7 +4,7 @@
|---|---|
| 状态 | 已定 |
| 日期 | 2026-08-04 |
| 相关 | [view.md](view.md) · 源目录 [`public/`](../../public/) |
| 相关 | [view.md](view.md) · [view-static-interactive.md](view-static-interactive.md)(静态交互 / 公式代码视觉 · Proposal) · 源目录 [`public/`](../../public/) |
---
+3 -3
View File
@@ -4,14 +4,14 @@
|---|---|
| 状态 | **v1(独立 debug 页)** |
| 日期 | 2026-08-05 |
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [pipeline-debug.md](pipeline-debug.md) |
| 相关 | [next-phase.md](../roadmap/next-phase.md) P3 · [view.md](view.md) · [view-document-annotations.md](view-document-annotations.md) · [pipeline-debug.md](pipeline-debug.md) |
## 分工
| 命令 | 角色 |
|------|------|
| `marqdo view` | 文档浏览器:Structure + Execution + Source;函数大纲与搜索;**无断点** |
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;**仅 live** |
| `marqdo view` | 文档浏览器:**叙述保真文档面** Structure + Execution + Source;函数大纲与搜索;跑后引出标注;**无断点**(见 [view-document-annotations.md](view-document-annotations.md)) |
| `marqdo debug` | 调试宿主(默认端口 **7430**):IDE 式布局;AST Structure + BP;**仅 live** |
静态 `gh-pages` / `view output` **不能**真断点。
+113
View File
@@ -0,0 +1,113 @@
# View:文档面与结果引出标注
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view.md](view.md) · [view-debug.md](view-debug.md) · [view-markup-surface.md](view-markup-surface.md) · [view-execution-trace.md](view-execution-trace.md) · [view-frame-selection.md](view-frame-selection.md) · [view-prose-annot-gaps.md](view-prose-annot-gaps.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 动机
`.mq.md` 是叙述与程序的同一载体。`marqdo view` 的 Structure 必须**保真叙述**,并在可执行标记旁展示运行结果。
旧 Browse Structure 用 AST 卡片重建语句,并用 `emit_comments` 只插入**语句行之前**的注释。当叙述与 `**…**` / `*…*` / `` `名` `` 在同一行时,该行被 Stmt 占用,叙述被丢弃——信息密度接近 debug,不适合文档浏览。
## 2. 模式分工
| 命令 | Structure | 叙述 | 结果 |
|------|-----------|------|------|
| `marqdo view`(Browse) | **文档面** | 保留并为主 | 跑后引出标注(callout + CSS L-leader) |
| `marqdo debug` | AST 卡片 + BP gutter | 弱化/可折叠 | Variables / 步进;不做文档 callout |
断点与逐步执行**仅**在 debug。静态 `view output` 与 live view **共用** Browse 文档面渲染。
## 3. 视觉语法
```
文本段…… `变量` …… **语句** …… *返回*
━━━━━
│
└──→ 结果标注
```
1. 叙述正文正常排版(Markdown)。
2. 可执行片段高亮,并带底部分割线(underline)。
3. 段落下方 **annotation band** 放结果 callout。
4. **CSS L-leader**(绝对定位小盒 + `border-left` + `border-bottom`)连接锚点与 callout。**不使用 SVG。**
5. 拥挤 / 极窄屏 / `prefers-reduced-motion`:取消长横折,改为编号 keyed 列表。
关联强度(递减):同色 underline + callout 色条 + label → CSS L-leader → keyed 编号。
对齐 [view.md](view.md) HIG:系统字体、无外链、浅色、克制装饰。
## 4. 文档面渲染
实现:`src/view/document.rs`;Browse 入口经 `render_module_structure` 调用。
| 源内容 | 呈现 |
|--------|------|
| 纯叙述段 | Markdown HTML;无 `comment` badge / 厚卡片 |
| 含 `ProseBit` 的行 | 原文保留;Decl / BoldCode / ItalicReturn 包 `mark.mq-anchor`(字节偏移来自 `scan_prose_line`) |
| 整行结构(`#` / `>` / `-` / `1.` / 表) | 表面语法保真(见 [view-markup-surface.md](view-markup-surface.md));整句可作锚点 |
| 函数标题 | 轻量 heading + `id="fn-{line}"`(大纲跳转不变) |
Debug 仍走 `render_module_structure_mode(..., Debug)` 的 AST 卡片路径。
## 5. ViewAnnot
跑后(或 `--no-exec` 时为空)组装标注集,嵌入文档面 `data-*` 与 band HTML。
| 字段 | 含义 |
|------|------|
| `id` | 稳定短 id(页内唯一) |
| `kind` | `bind` · `return` · `call` · `expr` · `branch` · `loop` · `writeback` |
| `anchor_line` | 1-based 源行 |
| `anchor_byte_start` / `anchor_byte_end` | 行内字节范围(可选;整行锚点可省略 end) |
| `label` | 短标题(名 / return / arm / loop) |
| `value` | 截断显示 |
| `detail` | 完整文本(inspect) |
| kind | 数据来源 | 锚点 |
|------|----------|------|
| `bind` | **StmtEvent post-stmt**(赋值执行后的值);禁止用入口终态回填初始化行 | 该赋值行 |
| `return` | 返回事件或入口返回 | ItalicReturn / Return |
| `call` / `expr` / `writeback` | writeback 槽、调用摘要 | 语句行或 BoldCode |
| `branch` | `ViewTrace`:命中 arm、次数 | 条件 / arm |
| `loop` | `ViewTrace`:迭代次数、末次 item | While / ForEach 头 |
标记面、结构块、多调用帧与 AI JSON 见 [view-execution-trace.md](view-execution-trace.md)。
`ViewTrace` 由 tree 解释器在 capture 时静默收集,**不**写入 stderr;与 `trace_eval` 调试轨迹分离。Bytecode 后端可暂无 trace(标注降级为 writeback)。
## 6. 布局与密度
- 每段默认最多 **4** 个常显 callout;其余 hover / 「show more」。
- Leader:按锚点 x 排序 callout,避免交叉;窄屏改为短竖线 + 堆叠。
- 客户端:`ResizeObserver` 重算 leader 盒的 `left/top/width/height`。
- 静态导出:页载 JS 跑一次布局。
右侧 **Variables** 仍为全集绑定;callout 为就地摘要,点击可打开同一 inspect。
## 7. 非目标
- 不在 view 内做断点 / 单步(见 [view-debug.md](view-debug.md))。
- 不新增作者侧标注 DSL / frontmatter 指令。
- 不引入外链字体、npm 组件或 SVG leader。
- 不把 DB/auth 等塞进 view 壳层。
## 8. 验收
1. `inc-prose.mq.md`:叙述「对于输入变量…」完整可见;`n` / `n=n+1` / 返回高亮。
2. 跑完后:值经 underline + CSS L-leader 连到下方标注(无 SVG)。
3. 分支/循环样例:可见命中 arm 与迭代次数(有 ViewTrace 时)。
4. `marqdo debug` 仍为 AST + 断点;叙述不抢主视觉。
5. 无外链字体/新依赖;`view output` 可离线打开。
## 9. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:文档面、ViewAnnot、CSS L-leader、与 debug 分工 |
| 2026-10-15 | bind = post-stmt;交叉链 view-execution-trace |
+103
View File
@@ -0,0 +1,103 @@
# View:执行轨迹与文档面保真
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [view.md](view.md) · [view-markup-surface.md](view-markup-surface.md) |
---
## 1. 目标
`marqdo view` Browse Structure 必须同时做到:
1. **标记面**:变量名 / 可执行语句 / 返回值按表面渲染(无源码定界符字面量)。
2. **结构块**:GFM 表、循环(`-`)、分支(`1.`)有正确 HTML 与缩进。
3. **语句后值**:赋值行标注该语句执行后的值,不用入口终态回填。
4. **执行臂**:高亮实际走的分支臂。
5. **多调用帧**:同函数多次调用可用下拉切换经历。
6. **AI 可读**:与 HTML 同源的 `ViewExecutionReport` JSON。
Debug 仍用 AST 卡片 + 断点;不做文档 callout。
## 2. 标记面
| 源标记 | 显示(无定界符) | class |
|--------|------------------|-------|
| `` `名` `` / `` `名`=默认 `` | `名`(默认次要后缀) | `mq-anchor mq-decl` |
| `**…**`(可执行) | 内层文本 | `mq-anchor mq-code` |
| `*…*`(返回) | 内层文本 | `mq-anchor mq-return` |
`data-byte-start/end` 仍为源码字节偏移(供 CSS L-leader)。软强调不进 anchor。
## 3. 结构块
| 块 | 呈现 |
|----|------|
| GFM 表 | `<table class="doc-table">` |
| `-` 循环 | `<ul class="doc-loop">`,体按源缩进 `--doc-indent` |
| `1.` 分支 | `<ol class="doc-branch">`;命中 `arm-taken`,未走 `arm-miss` |
| 公式 / 外联代码 | 现有 formula-card / code-card |
| `>` 调用 | 表面高亮,非整行灰 code |
## 4. StmtEvent / CallFrame
解释器 capture 时静默采集(非 `trace_eval` stderr):
```text
StmtEvent {
line, kind, // assign | return | call | branch | loop | bind_ref
name?, value_after?, // post-stmt 或求值结果
arm_index?, iter?,
call_id // 当前用户函数调用帧
}
CallFrame {
call_id, fn_name, fn_line, ordinal,
args_brief, // 短摘要供下拉
events[] // 或全局 events 用 call_id 过滤
}
```
- Assign → 写入后的值挂在**该行**。
- 循环内多次写入:UI 默认末次;可带次数。
- Branch → taken `arm_index` + 条件摘要。
- 进入用户函数分配 `call_id`;`# main` 单帧无下拉。
## 5. ViewExecutionReport(AI)
```json
{
"version": 1,
"path": "…",
"ok": true,
"calls": [{ "call_id": 1, "fn": "等级说明", "ordinal": 1, "args_brief": "等级=及格" }],
"events": [{ "line": 24, "kind": "assign", "name": "总分", "value_after": "0", "call_id": 0 }],
"bindings_final": { "均分": "73", "等级": "及格" }
}
```
产出:页内 `#mq-view-trace` JSON;live `GET /api/view-trace?path=`;SSE `done.trace_json`。
## 6. UI
- 函数标题旁 `<select class="call-picker">`(调用数 ≥ 2)。
- 循环头旁 `<select class="loop-picker">`(迭代数 ≥ 2);默认最后一轮;摘要 `分 = 分数表[i] · value`。
- **源码常显**:切换帧只改 chip / 臂高亮,不 `hidden` 结构节点。详见 [view-frame-selection.md](view-frame-selection.md)。
- CSS L-leader(非 SVG);拥挤 keyed 降级。
## 7. 验收
1. 无字面 `**` / 返回定界 `*` / 变量外层 `` ` ``(Source 除外)。
2. 表为真表格;循环/分支有缩进列表;未选中臂源码仍可见。
3. `总分 = 0` 标注 `0`,非终态累加。
4. 命中臂可视化;多调用下只显示当前帧的 taken。
5. 循环可按迭代切换;JSON 含 `loops`;单测覆盖。
## 8. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:标记面、结构块、StmtEvent、CallFrame、AI 报告 |
| 2026-10-15 | 帧选择保真:call_id 分支、LoopFrame、源码常显 |
+123
View File
@@ -0,0 +1,123 @@
# View:调用帧 / 循环帧选择与结构保真
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-execution-trace.md](view-execution-trace.md) · [view-document-annotations.md](view-document-annotations.md) |
---
## 1. 问题(对照实测)
1. **结构缺失**:切换函数调用下拉时,JS 按 `data-call-id` **隐藏** `.doc-exec`。未在本帧执行的分支臂体(赋值/返回)只有其它帧的 call_id,或仅有执行帧的 id → **未选中臂的源码被藏掉**,看起来像「臂消失 / 代码没渲染」。
2. **调用记录混叠**:`Branch` 标注未带 `call_id`;`taken_arms` 按行号只保留最后一次命中。多帧下同一分支同时出现 `arm 1 taken` 与 `arm 2 taken`。
3. **循环无帧**:循环只有总次数摘要;无法按迭代查看;`` - [分](分数表) `` 不能展示「当前是集合第几个元素」。
## 2. 定稿原则
| 原则 | 含义 |
|------|------|
| **源码常显** | 表 / 列表 / 分支臂 / 语句源码**永不**因帧选择 `hidden` |
| **轨迹随帧** | 标注 chip、臂高亮、变量值随「当前调用帧 / 当前迭代」变化 |
| **默认末帧** | 函数默认最后一次调用;循环默认最后一次迭代 |
| **一帧一真相** | 同时只展示一个 call_id(函数)或一个 (loop_id, iter)(循环)的轨迹 |
## 3. 函数调用帧
### 数据
`BranchHit` / 相关 `StmtEvent` 必须带 `call_id`。`ViewAnnot` 的 branch/bind/return 同样带 `call_id`。
### UI
- 函数标题旁 `<select class="call-picker" data-fn="…" data-scope="fn">`
- 选项:`1: 等级=及格` / `2: 等级=优秀`
- 默认选中最后一次
### 客户端(`applyCallFrame`)
1. 读 `#mq-view-trace` JSON。
2. 过滤 `events` where `call_id == selected`。
3. **不**设置结构节点 `hidden`。
4. 更新该函数作用域内:
- `.annot-chip[data-call-id]`:仅显示匹配帧;无 call_id 的结构说明类可保留
- `.doc-branch[data-line]`:按该帧的 branch 事件设置 `arm-taken` / `arm-miss`(全部臂仍可见)
- 绑定 chip 的 `.annot-value`:用该帧 assign/return 事件刷新(同名同行取末次)
## 4. 循环迭代帧
### 数据
```text
LoopFrame {
loop_id, line,
item_name?, // "分"
collection?, // "分数表"
iterations: [{ index, item_value, call_id }] // index 0-based
}
```
`StmtEvent` 增加可选 `loop_id`;循环体内事件带 `iter`(1-based 或 0-based,JSON 内统一 **0-based index**)。
### UI
- 循环头(`- [分](分数表)`)旁:`<select class="loop-picker" data-loop-id="…">`
- 选项:`迭代 1: 分=92` … `迭代 4: 分=88`
- 默认最后一次
- 头旁摘要 chip:`分 = 分数表[3] · 88`(下标 0-based 显示为 `[i]`)
### 客户端(`applyLoopFrame`)
1. **只显示当前迭代**:带 `data-iter` 的 chip 仅保留选中项;其余 `hidden` + `is-frame-hidden`(SSR 默认已按末轮预隐藏)。
2. 更新头摘要 chip(无 `data-iter`)为当前选项文案。
3. 不隐藏循环体源码。
## 5. 分支臂渲染
- 所有臂(含 else)**始终**渲染完整头 + 体(含 `*返回*` / 赋值)。
- `arm-miss` 仅降低不透明度,**不** `display:none` / `hidden`。
- 高亮仅反映**当前帧**的 taken `arm_index`。
## 6. AI JSON 增量
`ViewExecutionReport` 增加:
```json
"loops": [{
"loop_id": 1,
"line": 27,
"item": "分",
"collection": "分数表",
"iters": [{ "index": 0, "value": "92" }, { "index": 3, "value": "88" }]
}]
```
`events[].call_id` 必填;循环体内事件带 `loop_id` + `iter`(index)。
## 7. 验收
1. 未选中分支臂源码始终可见(含返回句)。
2. 切换「等级说明」调用:只显示该帧的 arm taken;变量/返回值对应该帧。
3. 循环下拉默认最后一轮;`分 = 分数表[3] · 88`;切换迭代后体内累加值变化。
4. `#mq-view-trace` 含 `loops` 与带 `call_id` 的 branch 事件。
5. `cargo test --lib view::` 全绿。
## 8. 开发计划(已执行)
| 阶段 | 内容 | 状态 |
|------|------|------|
| D0 | 本文档 + `view-execution-trace.md` 交叉引用 | ✅ |
| D1 | `BranchHit.call_id`;`LoopFrame` / `LoopIter`;`StmtEvent.loop_id` | ✅ |
| D2 | 解释器:foreach/while 推栈;BindRef `分=分数表[i]`;assign 带 iter | ✅ |
| D3 | `build_view_annots`:分支带 call_id;LoopFrame 选项;报告 JSON `loops` | ✅ |
| D4 | 文档面:源码不贴 `data-call-ids`;call picker `value=call_id`;loop picker;SSR taken=末帧 | ✅ |
| D5 | JS:`applyCallFrame` / `applyLoopFrame` — 只滤 chip + 重算 arm,不 hidden 结构 | ✅ |
| D6 | 单测:多调用不同臂、loop 末项、HTML 三臂返回 + picker | ✅ |
## 9. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:源码常显、帧过滤、循环迭代 picker |
| 2026-10-15 | 按计划落地 D1–D6 |
+145
View File
@@ -0,0 +1,145 @@
# View:叙述面标注缺口(prose annot gaps)
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [view-frame-selection.md](view-frame-selection.md) · [view-execution-trace.md](view-execution-trace.md) |
> **定位**:对既有文档面设计的**缺口专章**——写清用户可见的四类问题、根因(文件:行)与验收口径。不改写 ADR;不发明作者侧标注 DSL。
---
## 1. 为何「改了却几乎没变化」
| 原因 | 说明 |
|------|------|
| 错二进制 | PATH 上的 `marqdo` 可能仍是旧版(如 1.3.0);改动在源码 / `./target/debug/marqdo`。验收必须用 `cargo build && ./target/debug/marqdo view …` |
| Chip 被溢出藏掉 | 同 band 堆多帧 return/print/who;`MAX_VISIBLE_ANNOTS=4` 把当前帧的 `who` 打成 `annot-chip-overflow`(`display:none`);帧切换不重算溢出 |
| L-leader 几何错位 | `initAnnotLeaders` 里 `y0=0` 只在 `.annot-band` 顶画短折,**连不到**上方 underline;窄屏或 chip>4 时整段关掉 leaders |
| 旧静态快照 | gh-pages / 旧 `view output` 不会自动刷新 |
---
## 2. 目标视觉语法(既有,不新造)
锚定 [view-document-annotations.md](view-document-annotations.md) §3:
```
文本段…… `变量` …… **语句** …… *返回*
━━━━━
│
└──→ 结果标注 chip
```
- underline:`mark.mq-anchor.mq-{decl|code|return}`
- band:段落下方 `.annot-band` → leaders + chips
- L-leader:CSS `border-left` + `border-bottom`(禁止 SVG)
- 公式/代码:[view-static-interactive.md](view-static-interactive.md) G3 **一层主视觉**;卡下不叠 Bind dump
- 帧:[view-frame-selection.md](view-frame-selection.md) **源码常显、只滤 chip**;默认末帧
---
## 3. 管线
```mermaid
flowchart LR
CLI["marqdo view / view output"] --> build["build_file_view"]
build --> cap["run_file_capture"]
cap --> annot["build_view_annots"]
annot --> doc["document::render_module_document"]
doc --> page["html.rs page_file"]
page --> js["initAnnotLeaders + initCallPickers"]
```
| 步骤 | 位置 |
|------|------|
| CLI / 导出 | `src/main.rs` · `src/view/mod.rs` · `src/view/output.rs` |
| Capture + Call 事件 | `src/interp.rs` |
| Annot 组装 | `src/view/annot.rs` `build_view_annots` |
| 文档面 HTML | `src/view/document.rs` |
| 卡片 chrome | `src/view/render.rs` `render_*_assign_card` |
| CSS / leader JS | `src/view/html.rs` |
---
## 4. 四条用户问题 → 根因 → 验收
复现源:`public/00-welcome.mq.md` · `public/00-欢迎.mq.md`
对照金样:`tests/view/document-annot-demo.mq.md` · `tests/markup-v03/inc-prose.mq.md`
### P1 — 叙述与代码同段时信息不显示
| | |
|---|---|
| 现象 | underline 在,chip / 连线弱或无 |
| 根因 | `html.rs` `initAnnotLeaders`:`y0=0` 相对 band;`document.rs` `MAX_VISIBLE_ANNOTS` 把当前帧 chip 溢出;PATH 旧 CLI |
| 目标 | 同 `inc-prose`:underline + L-leader(从锚点底到 chip)+ 可见 chip |
| 验收 | `./target/debug/marqdo view public/00-welcome.mq.md`:主文 `**greet…**` 与 `## greet` 体内均有可见 chip 与接到 underline 的 leader(宽屏) |
### P2 — 函数内变量不显示
| | |
|---|---|
| 现象 | `` `who` `` 有浅蓝 underline,无值 chip |
| 根因 | bind chip 存在但带 `annot-chip-overflow`;`applyCallFrame` 只 `hidden` 非选中帧,不解除当前帧 overflow |
| 目标 | 选中调用帧时常显 `who` · `print` · `return` 各一枚 |
| 验收 | 切换「调用」下拉,三枚 chip 随帧变且默认可见(无需点 +N) |
### P3 — ` ```text ` 渲染不一致
| | |
|---|---|
| 现象 | 变成内联 `text marqdo ext add…`,无卡片 |
| 根因 | Comment 围栏若进 `flush_para` → `join(" ")` → pulldown 当 inline code;应走 `render_narrative_fence` |
| 目标 | 与 bound python 同 `.code-card` chrome(badge + `pre.code-body`),**无** Run/foot |
| 验收 | welcome install 段:`data-lang="text"` + 两行 `marqdo ext add`;无 `<code>text marqdo` |
### P4 — 函数引用 / 代码卡未渲染
| | |
|---|---|
| 现象 | `**greet who=…**` 无结果;或 `hi` python 只见头/Run、不见源码 |
| 根因 | 同行多 Call 未与 BoldCode zip;或 Run 挤在 head;静态假 Run;错看 Debug 路径 |
| 目标 | 主文两 greet 各有 call chip(stdout 摘要);`hi` = `render_code_assign_card` head→body→foot;静态藏 Run |
| 验收 | 两枚 greet mark 均有非空 `data-annot-id`;`code-body` 含 `hello-from-python`;`MARQDO_VIEW_LIVE=false` 无 Run 按钮 |
### call_id 语义(写死)
| 位置 | call_id |
|------|---------|
| 主文 `**greet…**` 的 call chip | 入口帧(`# main` 的 call);结果为 stdout/返回摘要 |
| `## greet` 体内 print / who / return | callee 的 CallFrame id;跟函数标题旁 picker |
---
## 5. 修复约定(实现红线)
1. **帧感知密度**:band 内按选中 `call_id` 计可见 chip;默认末帧;同帧最多 4 枚常显;溢出只藏非当前帧或多余 kind。切换后客户端重算 overflow + `layoutAll()`。
2. **Leader 容器**:提升到 `.doc-block`(prose + band);`y0` = 锚点底相对 block;按锚点 x 排序再画线。
3. **卡片**:只复用 Browse `render_*_assign_card` / `render_narrative_fence` + `html.rs` `.code-*` / `.formula-card`;本波不改 Debug AST 路径(除非回归红)。
4. **静态 Run**:`MARQDO_VIEW_LIVE=false` 时隐藏 Run,不留禁用假按钮(对齐 view-static-interactive D5)。
5. **非目标**:不做 debug 断点;不发明作者标注 DSL;不用 SVG leader;不单独发版/推 gh-pages(除非另嘱)。
---
## 6. 验收命令
```bash
cargo build -q
./target/debug/marqdo version # 须为当前工作树版本
./target/debug/marqdo view public/00-welcome.mq.md --no-open
./target/debug/marqdo view tests/view/document-annot-demo.mq.md --no-open
cargo test -q --lib view::
```
---
## 7. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:四问题、错二进制/溢出/leader 根因、帧感知密度与 leader 几何约定 |
| 2026-10-15 | L-leader 拥挤/消失:同跨度多帧 chip **共用 annot id**;可见 chip 按锚点 x 重排;leader 挂 doc-block |
| 2026-10-15 | L-leader 黑线碎段:JS `border*: "1.5px solid"` 无色覆盖 class → 改为 kind 色写入 shorthand;chip SSR/DOM 按锚点 L→R |
| 2026-10-15 | L-leader 改为 SVG:描述底边中点 → 轨道 → 短竖线 → 值 chip 顶边中点;chip 间距加宽 |
+239
View File
@@ -0,0 +1,239 @@
# View:静态页交互与公式/代码卡视觉
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-10-15 |
| 相关 | [view.md](view.md) · [user-site.md](user-site.md) · [view-document-annotations.md](view-document-annotations.md) · [view-frame-selection.md](view-frame-selection.md) · [ADR 0002 browser WASM](../adr/0002-browser-marqdo-wasm.md) |
**已确认(2026-10-15)**
| 决策 | 选择 |
|------|------|
| 引擎 | **B**(快照 + S1 帧切换 + 可选懒加载 WASM S2) |
| 体验原则 | 静态页与 live view **尽量同构**;控件形态对齐;无服务端时用 WASM/JS 补齐 |
| 视觉原则 | **一层主视觉**;一眼能懂;公式/代码不与 Bind chip / 源残留叠床架屋 |
| 演示参数条 | **要**(历史实参 select + 可编辑;S1 切帧 / S2 重跑) |
| code-card Run | 有 WASM 时可用;否则隐藏(不对齐「假按钮」) |
| 公式 Bind chip | **卡内不显示**;Variables 可留终值 |
---
## 1. 动机(对照 `public/00-欢迎.mq.md` / gh-pages)
静态导出(`marqdo view output` → `gh-pages`)与 live `marqdo view` 已共用**文档面 Structure** 渲染路径,但用户站实测仍有三类落差:
1. **交互控件缺失 / 偏弱**
- 函数「问候」仅有参数 chip「谁」,没有可切换的调用帧下拉(即便源里 `> 问候` 写了两次)。
- 参数行 `+ 谁` 在文档面呈声明高亮,读者无法在静态页改「谁」并看到新输出。
- 外联 `code-card` 的 Run 在静态模式被禁用(`Run is available in live marqdo view`)。
- 静态 stdin 仅在有 preset 时显示只读提示,**不能**再跑。
2. **无服务端时仍可交互的预期**
用户站是纯静态托管:没有 `/api/run`。合理路径是 **页内 JS** 和/或 **嵌入 Marqdo WASM**,在浏览器里重算 Structure 标注、Execution 区,甚至模拟 `input` / 外联(沙箱约束另定)。
3. **公式 / 代码块视觉凌乱**
同一赋值同时出现多层表象,信息重复、线框错位:
| 层 | 公式 `f = $$…$$` | 外联 `hi = ```python…``` |
|----|------------------|---------------------------|
| A 卡片 | `formula` badge + KaTeX | `code` badge + 高亮源码 + cmd/Run |
| B 标注 chip | `f` → `x^2 - 2` | `hi` → 整段 fence 摘要 |
| C 源残留 | 卡片外/旁再露 `$$` 或 ASCII | 卡片下再露 `python print…` 明文 |
再叠加 CSS L-leader 与卡内边框,首屏显得碎、重复、「坏掉的线」。
**本文件只定问题与方案;确认前不改代码。**
---
## 2. 现状解剖
### 2.1 静态 vs live(同一 `page_file`)
| 能力 | Live | Static(`LinkMode::Static`) |
|------|------|------------------------------|
| 文档面 Structure + annot | ✅(跑后) | ✅(导出时跑后写入) |
| call / loop picker JS | ✅(读 `#mq-view-trace`) | ✅(同源 JS;若轨迹未写入则无控件) |
| `/api/run` · Stream | ✅ | ❌ |
| stdin 表单 | ✅ 可再跑 | 只读 hint(或无) |
| code-card Run | ✅ `POST` 外联 | ❌ 禁用按钮 |
| WASM 重算 | ❌(未接) | ❌(未接) |
结论:**不是「静态另做一套皮肤」**,而是「导出瞬间的快照 + 部分 JS 帧切换」;**没有**浏览器内重执行闭环。
### 2.2 欢迎页结构(问题复现源)
```text
> 问候 谁=marqdo
> 问候 谁=marqdo user
## 问候
+ `谁`
> 打印 内容=欢迎,`谁`!
`f` = $$ x^2 - 2 $$
`hi` = ```python … ```
```
- 期望:`## 问候` 旁 **调用** 下拉(`1: 谁=marqdo` / `2: 谁=marqdo user`),切换时打印行的绑定/输出随帧变。
- 现状风险:若导出时 CallFrame &lt; 2、或 picker 未挂上、或读者期望的是「编辑谁」而非「选历史调用」,都会表现为「没有下拉框」。
- 公式/代码:`SpecialAssign` → formula/code **card**,同时又对同名绑定建 **Bind annot**,文档面还可能保留块源视觉 → 三重展示。
### 2.3 已有红线(方案不得破坏)
- 代码即文档:`.mq.md` 源可读;不发明第二套嵌套 DSL(见 web-artifact / marqdo-dev)。
- Browse ≠ Debug:静态站不做断点。
- `public/**/*.html` 不入库;gh-pages 由 CI/`view output` 生成([user-site.md](user-site.md))。
- 外链字体禁令仍在 [view.md](view.md);WASM/重型资源须 **可选加载**,默认站可降级为纯快照。
---
## 3. 目标(验收口径)
### G1 — 帧与参数交互(静态可读、可拨)
1. 同函数 ≥2 次调用时,静态页 **必有**「调用」下拉;默认末次;切换只改 chip/臂/相关输出,**源码常显**(同 [view-frame-selection.md](view-frame-selection.md))。
2. 导出保证写入完整 `#mq-view-trace`(含 `calls` / `events` / 可选 `loops`)。
3. (增强)演示向参数可提供 **受控输入**:默认值来自末次调用或 FM;改参后可触发页内重算(见 §5 引擎选项)。
### G2 — 无服务端可重算(可选引擎)
| 档位 | 能力 | 依赖 |
|------|------|------|
| **S0 快照**(现状加强) | 导出时跑完;帧 picker;只读 Execution | 无 WASM |
| **S1 页内重放轨迹** | 不重跑程序,只切换已序列化帧/标注 | JSON only |
| **S2 WASM 重跑** | `marqdo_wasm` + bridge:改 stdin/实参后重跑,刷新 Structure/Execution | WASM 包(可 CDN/`public/wasm/`) |
| **S3 外联沙箱** | code-card Run:浏览器内 pyodide **或** 明确标「仅 live」 | 可选;默认可关 |
默认用户站:**S0 + S1 必达**;**S2 为推荐主路径**(与「用 wasm 模拟输出」对齐);S3 单独开关。
### G3 — 公式 / 代码视觉单层真相
对「特殊赋值」块约定 **一层主视觉 + 至多一层结果**:
| 块 | 主视觉 | 允许的结果层 | 禁止 |
|----|--------|--------------|------|
| 公式 | KaTeX(formula-card 精简) | 无 Bind chip,或仅在 Variables | 再渲一份 `$$` 明文;annot 与卡重复同一 TeX |
| 外联代码 | 高亮源码(code-card) | 运行输出区 `code-out`;静态可藏 Run 或接 S2/S3 | annot 再贴整段 fence;卡下重复裸源 |
| 普通赋值 | 标记面语句 | Bind chip + L-leader | — |
Leader:仅连接「主视觉锚点 → 唯一结果 chip」;卡内不用第二套 L 线。
---
## 4. 问题清单(成文)
| ID | 问题 | 严重度 | 根因假设 |
|----|------|--------|----------|
| P1 | 静态页看不到调用/循环下拉 | 高 | 轨迹未导出完整 / picker 条件(≥2)未满足 / 读者要的是编辑参而非选帧 |
| P2 | 不能改参/stdin 再看输出 | 高 | Static 禁用 `/api/run`;无 WASM 闭环 |
| P3 | code-card Run 静态无效 | 中 | `initForeignCards` 显式禁用 |
| P4 | 公式卡 + chip + `$$` 三重 | 高 | card 与 Bind annot 叠加;块源未完全被 SpecialAssign 吞掉 |
| P5 | 代码卡 + chip + 明文三重 | 高 | 同 P4 |
| P6 | 卡内/旁碎线、错位 | 中 | leader 锚到错误节点;卡 CSS 与 annot-band 叠层 |
| P7 | 静态 stdin 体验差 | 中 | 仅有只读 hint |
---
## 5. 解决方案(详案,待选)
### 5.1 引擎策略(三选一,推荐 **B**)
| 方案 | 做法 | 优点 | 代价 |
|------|------|------|------|
| **A. 纯快照 + S1** | 加强导出轨迹与 picker;不引入 WASM | 体积小、离线稳 | 不能改参真重算 |
| **B. 快照默认 + 可选 WASM(S0/S1/S2)** | `view output` 仍嵌入跑后 HTML;页脚/侧栏「在浏览器中重跑」懒加载 WASM;改参后 patch Structure/Execution | 对齐用户预期;无 WASM 时仍可读 | 打包/加载体积;宿主能力子集 |
| **C. 静态页全面 WASM 首屏** | 打开即 WASM 跑 | 交互最强 | 冷启动慢;gh-pages 带宽;与「文档先可读」冲突 |
**推荐 B**:文档先可读(S0),帧切换不依赖 WASM(S1),需要改参/演示时再拉 WASM(S2)。
### 5.2 交互控件(与文档面一致)
1. **调用 / 循环 picker**(已有组件)
- 导出验收:欢迎页「问候」必须出现调用下拉。
- 单测:对 `00-欢迎.mq.md` / `document-annot-demo` 断言 HTML 含 `call-picker` 且 options≥2。
2. **演示参数条(新,窄范围)**
- 仅当函数被标记为「可演示」**或**静态页检测到 ≥1 形参且存在 CallFrame 时,在函数标题旁增加:
`谁 [ text input | select(历史实参) ] [应用]`
- **不**改 `.mq.md` 语法;数据来自 trace 的 `args_brief` / 末次绑定。
- 「应用」:S1 仅切换已有帧;S2 调 WASM `run` 后替换 `#structure` / Execution。
3. **stdin**
- 静态:若源含 `input`,渲染与 live 同形的 textarea +「重跑」(S2)或说明「需 WASM」。
- 无 input 则不显示。
### 5.3 公式 / 代码去重(视觉)
**规则:SpecialAssign 行只走 card,不再为同名同值挂 Bind chip。**
```text
公式赋值行
└─ formula-card(badge + 名 + KaTeX)
└─ ✗ 不再 render_annot_band(Bind f)
└─ ✗ 不再在卡外输出 $$ 源
外联赋值行
└─ code-card(badge + 名 + 高亮体 + 可选 Run)
└─ ✗ 不再 Bind chip 贴 fence 全文
└─ 运行结果只进 .code-out
```
静态 Run 策略(与 §5.1 对齐):
- S0:隐藏 Run,或保留禁用并 tooltip「打开 live view / 启用 WASM」。
- S2:Run → WASM 宿主 `foreign`(若 WASM 支持)或提示不支持。
- S3:可选 Pyodide(默认关)。
CSS:formula-card / code-card 与 `.annot-band` 垂直节奏统一;禁止对 KaTeX 节点拉 L-leader。
### 5.4 导出管线
```text
marqdo view output
→ build_file_view(跑 + annot + trace_json) // 已有
→ page_file(Static)
+ 嵌入 #mq-view-trace
+ (可选)data-wasm-url / 懒加载脚本
+ 公式/代码去重后的 structure_html
→ public/ + gh-pages
```
`--no-exec`:文档面无标注;可提示「本页为结构-only」;S2 仍可尝试 WASM 首跑(可选,默认关以免惊喜执行)。
### 5.5 明确不做(本提案)
- 静态页断点调试(仍属 `marqdo debug`)。
- 在 `public/*.mq.md` 发明新的「交互表」DSL(除非另开设计并获批)。
- 默认全站加载 Pyodide。
- 提交生成 HTML 进 `main`。
---
## 6. 分阶段开发计划(确认后执行)
| 阶段 | 内容 | 交付 | 依赖确认 |
|------|------|------|----------|
| **D0** | 本文定稿;选定引擎 **A/B/C**;是否要「演示参数条」 | 状态 → Active | **本次决策** |
| **D1** | P4/P5/P6:SpecialAssign 与 Bind 互斥;卡 CSS;去掉重复源 | 欢迎页公式/代码干净;单测 | D0 |
| **D2** | P1:导出轨迹验收 + 欢迎页 call-picker 金样;修任何「≥2 调用无下拉」bug | HTML 断言 | D0 |
| **D3** | P2/P7 S1 夯实:静态 stdin UI 形态;无 WASM 时文案清晰 | UX | D0 |
| **D4** | (若选 B)S2:静态页懒加载 WASM;「应用参数 / 重跑」刷新 Structure+Execution | `public/wasm` 或 CDN 策略;体积预算 | D0=B |
| **D5** | P3:code-card 与 S2/S3 策略落地;默认隐藏无效 Run | — | D1+D4 |
| **D6** | `build-public` / pages CI 回归;更新 [user-site.md](user-site.md) · [view.md](view.md) 验收条 | gh-pages 抽检欢迎页 | D1–D5 |
建议默认路径:**D0 选 B → D1 → D2 → D3 → D4 → D5 → D6**。
---
## 7. 决策记录
见文首「已确认」。开发按 §6:D1 → D2 → D3 → D4 → D5 → D6。
---
## 8. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-10-15 | 初稿:静态交互缺口、公式/代码凌乱、S0–S3 与阶段 D0–D6 |
| 2026-10-15 | Active:引擎 B;对齐 live;干净视觉;演示参数条;Run 接 WASM 否则隐藏 |
+6 -4
View File
@@ -4,7 +4,7 @@
|---|---|
| 状态 | 已定(v0.0.2 方向) |
| 日期 | 2026-08-04 |
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [view-markup-surface.md](view-markup-surface.md) · [view-document-annotations.md](view-document-annotations.md) · [view-static-interactive.md](view-static-interactive.md) · [generated-yaml-manifest.md](generated-yaml-manifest.md) · 视觉参考 [id.cflmy.cn](https://id.cflmy.cn) |
---
@@ -77,7 +77,7 @@ OUT_DIR/
- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。
- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。
- 渲染逻辑与实时 `view` **共用**同一套 HTML 构件(结构 / 执行 / 源码),禁止两套皮肤分叉。
- 渲染逻辑与实时 `view` **共用**同一路径:`build_file_view` → 文档面 Structure(`document.rs` + annots)→ `page_file`(同一 CSS/JS,含 call/loop picker、`#mq-view-trace`)。禁止第二套皮肤。`--no-exec` 时仍出文档面,但无运行标注。
示例:
@@ -90,14 +90,16 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc
## 4. 信息架构
侧栏文件索引 + 主区:结构(AST+注释)· 执行 · 源码。结构旁**右侧栏**(现有 outline 槽)为:
侧栏文件索引 + 主区:**文档面 Structure** · 执行 · 源码。Structure(Browse)为叙述保真文档面:标记面(变量/语句/返回无源码定界符)、表/列表/分支结构保真,跑后结果经 **CSS L-leader** 引出——见 [view-document-annotations.md](view-document-annotations.md) · [view-execution-trace.md](view-execution-trace.md)。**不是** AST 卡片栈(那是 debug)。
结构旁**右侧栏**(现有 outline 槽)为:
| 区块 | 内容 |
|------|------|
| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) |
| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) |
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板。
view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板;终态亦可刷新 Structure 内标注。
表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。
@@ -0,0 +1,58 @@
# 缺陷记录:LLM 传输失败硬中断 Agent Runtime
| | |
|---|---|
| 状态 | **Fixed(2026-10-16)** — 见 §3;金样 `tests/ext/agent-llm-transport-soft.mq.md` |
| 日期 | 2026-10-16 |
| 发现方 | qdagent(接通 `agent.run` live 路径时) |
| 影响面 | `host/net` · `plugins/llm` · `ext/ai/llm` · `ext/ai/llm/openai` · `ext/ai/agent` |
| 相关 | [agent-run-efi-resolve-bugs-2026-10.md](agent-run-efi-resolve-bugs-2026-10.md) · [ext-agent.md](../design/ext-agent.md) |
---
## 0. 一句话
上游 LLM **连接拒绝 / 超时 / 非 200** 时,Runtime 曾以 **硬错误** 终止整个 `marqdo run`;产品(qdagent ASK/BUILD)无法落到结构化 `status=error`。
---
## 1. 复现
```bash
OPENAI_API_KEY=offline OPENAI_BASE_URL=http://127.0.0.1:9 \
marqdo run tests/ext/agent-llm-transport-soft.mq.md
# 修复前:exit≠0,error: http POST …
# 修复后:exit 0,ask/step/run 均带 finish|status=error + error 文本
```
---
## 2. 根因
| 层 | 行为 |
|----|------|
| `host_http_post` / SSE | 传输失败 `Err(...)` → VM abort |
| `plugins/llm` `llm_chat_completions` | 同上 `Err` |
| `ext/ai/llm/openai` | HTTP≠200 → `sys.exit 1` |
| `agent.model_turn` / `step` / `plan` | 无软失败臂 |
---
## 3. 修复清单
| # | 改动 | 文件 |
|---|------|------|
| 1 | 传输失败 → `{status:0, body}` / SSE error event | `src/host/net.rs` |
| 2 | 插件返回 `{finish:error, error, …}` 而非 `Err` | `plugins/llm/src/lib.rs` |
| 3 | openai 非 200 → 结构化 pack,禁止 `sys.exit` | `ext/ai/llm/openai.mq.md` |
| 4 | `llm.ask` 透传 `error` / `finish` | `ext/ai/llm.mq.md` |
| 5 | `model_turn` / `step` / `plan` 收成 `status=error` | `ext/ai/agent.mq.md` |
| 6 | 金样 | `tests/ext/agent-llm-transport-soft.mq.md` |
**契约**:Agent Runtime 对 LLM 传输失败必须可捕获;`status=error` + `error` 字符串;进程退出码 0(程序正常返回错误图)。
---
## 4. 对 qdagent
`ensure_llm` 有 key 但上游不可达时,`ask`/`build` 可走既有 `mode=error` 臂写 workbook,不再整 CLI 崩。
@@ -0,0 +1,117 @@
# 缺陷记录:`agent.run` EFI / resolve 在消费方崩溃(qdagent 复现)
| | |
|---|---|
| 状态 | **Fixed(2026-10-16)** — 见 §3;金样 `tests/ext/agent-run-cold-efi.mq.md` |
| 日期 | 2026-10-16 |
| 发现方 | qdagent(`~/work/qdagent`)接通 Marqdo ≥1.4.2 Agent EFI 全路径时 |
| 影响面 | `ext/ai/agent` · `## run` · `plugins/agent` `agent_resolve` |
| 相关 | [ext-agent.md](../design/ext-agent.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) |
---
## 0. 一句话
`agent.run` 在 **空 OKF / 无 skill 命中** 或 **`efi=True`** 时,会以硬错误退出,而不是降级到 `plan` 探索。
这是 **Agent Runtime 契约不完整**,不是 qdagent 业务写错。
---
## 1. 复现(qdagent)
环境:工作区 Marqdo `1.4.2` + `MARQDO_EXT=~/work/marqdo/ext`;qdagent 调用:
```text
助手 = > agent.agent …
`助手`.run task=… efi=True # 或 efi=False 后仍进 resolve
```
本仓几乎没有 `.marqdo/agent-kb` 编译 skill。
### Bug A — `efi=True` → `unknown function preflight`
**位置**:[`ext/ai/agent.mq.md`](../../ext/ai/agent.mq.md) `## run`
```markdown
1. `efi`
**efi_pf = preflight task=`task`**
```
同文件其它同对象方法一律写 `` `self`.route `` / `` `self`.resolve ``。
裸标识 `preflight` 在导入消费方(如 `cli/求道-构建.mq.md`)里被解析成**全局函数**,找不到 → 硬错。
**期望**:`` **efi_pf = > `self`.preflight task=`task`** ``(或等价 method call)。
### Bug B — miss resolve → `missing map key llm_free`
**位置**:
1. Plugin:[`plugins/agent/src/memory.rs`](../../plugins/agent/src/memory.rs) `resolve_task`
当 `kb_lookup` 返回 null:
```rust
Ok(json!({
"mode": "unknown",
"skill": null,
"resource": null,
"confidence": 0.0,
// 缺 llm_free
}))
```
2. Facade:`## run` 在 resolve 之后:
```markdown
**llm_free = [llm_free](resolved)**
```
脚注式取键在缺键时 **硬失败**,无法落到后面的 `plan` 探索臂。
**期望**:
- miss 结果始终带 `"llm_free": false`(与命中路径字段集对齐)
- facade 侧对可选键用 `json.get`(缺省 `False`),防御其它调用方
---
## 2. 为何金样没拦住
| 金样 | 为何漏网 |
|------|----------|
| `tests/ext/agent-zero-llm.mq.md` | 先编译 skill / policy,再 `run`;resolve **命中** |
| `tests/ext/eng-preflight.mq.md` | 只测 `agent_eng_preflight`,**不**走 `agent.run efi=` |
| 多数 `agent-*-live` | 自带 kb 或 `efi=False` / 不经过 cold miss |
qdagent 是第一个「冷库 + 产品 EFI + `run`」消费方,因此打穿。
---
## 3. 修复清单(本轮)
| # | 改动 | 文件 |
|---|------|------|
| 1 | miss resolve 补 `llm_free: false` | `plugins/agent/src/memory.rs` |
| 2 | `` `self`.preflight ``;`llm_free`/`mode` 用 `json.get` | `ext/ai/agent.mq.md` |
| 3 | 回归金样:冷 kb + `run efi=True` 不崩溃,落到 explore/plan | `tests/ext/agent-run-cold-efi.mq.md` |
| 4 | 重建 `marqdo_plugin_agent` 并跑金样 | `cargo build -p marqdo_plugin_agent --release` |
---
## 4. 对 qdagent 的含义
修复后 qdagent 可恢复:
```text
product preflight → latch → agent.run (efi=True|False) / plan
```
而不必长期绕开 `agent.run`。
在插件未装入新 so 前,qdagent 侧 EFI latch + `step`/`plan` 仍是合法降级。
---
## 5. 非目标
- 不改 EKC / `agent_eng_preflight` 语义
- 不引入第二套 Agent loop
- 不把向量检索升为权威真相
@@ -0,0 +1,136 @@
# 调研:代码即文档 × OKF × 沙盒 下的智能体 / 大模型优化(2026-10)
| | |
|---|---|
| 状态 | **调研 + 问题分析 · 供方案 [ext-ai-optimize.md](../design/ext-ai-optimize.md) 参考** |
| 日期 | 2026-10-16 |
| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [agent-framework-2026-09.md](agent-framework-2026-09.md) · [ai-agent-sandbox.md](ai-agent-sandbox.md) · [okf-and-marqdo.md](okf-and-marqdo.md) |
| 本仓能力 | [ext-agent.md](../design/ext-agent.md) · [okf.md](../design/okf.md) · [engineering-knowledge.md](../design/engineering-knowledge.md) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) |
| 外部抽样 | Anthropic Agent Skills · SoK Agentic Skills (arXiv 2602.20867) · ForgeAgent · ACES / Skill Lift · Switchcraft 路由 · DSPy/GEPA ·「工作流编译进权重」· MalSkillBench |
---
## 0. 一句话
业界正把 Agent 优化从「更好的 chat loop」转向 **可验证、可复用、可隔离执行的技能层**;Marqdo 已具备 **可执行 Markdown(代码即文档)+ OKF/EKC 复用 + CoW 沙盒** 三件套,优化目标应是把这三件套焊成闭环:**试跑 → 证据 → 晋升 → 零/少 LLM 复用**,而不是追平 LangChain 功能清单。
---
## 1. 调研方法
| 动作 | 说明 |
|------|------|
| 扫业界技能层 | Anthropic Skills(渐进披露 `SKILL.md`);SoK Agentic Skills 生命周期;ForgeAgent「能力铸造」;ACES Skill Lift |
| 扫成本/路由 | Switchcraft 工具调用路由;DSPy+GEPA 提示优化;工作流编译进小模型权重 |
| 扫安全 | MalSkillBench 运行时验证恶意技能;沙盒粒度讨论(per-skill / per-session) |
| 对照本仓 | A0–A4 / Wave B 已落地;沙盒 S0–S4 已落地;OKF + EKC + adaptive routing 现状 |
**不修改** `doc/next/*`(手写真相源);本文件只进 `doc/research/`。
---
## 2. 业界态势(与 Marqdo 相关的收敛点)
### 2.1 技能层取代「纯工具调用叙事」
| 来源 | 要点 | 对 Marqdo |
|------|------|-----------|
| Anthropic Agent Skills | 目录 + `SKILL.md`;元数据预载、正文按需;脚本可执行 | 形态近 OKF 任务包,但 Marqdo 技能 **本身可跑** |
| SoK Agentic Skills | 发现→练习→蒸馏→存储→组合→评测→更新;代码技能需沙盒 | 生命周期与 OKF promote / sandbox.run 对齐 |
| ForgeAgent | 生成能力 → 沙盒证明 → 信任复用;失败进回归隔离 | **验证后晋升** 正是 solidify / `llm_free` 缺的硬闸 |
| ACES | 有/无技能配对试验 → Skill Lift | 可作 Marqdo 评测 harness 指标 |
### 2.2 成本:路由 + 编译 + 小模型
| 来源 | 要点 | 对 Marqdo |
|------|------|-----------|
| Switchcraft | 工具调用场景路由到最便宜仍正确的模型;报道大幅降本 | 已有 `marqdo \| small-llm \| llm \| auto`;可加 **工具步/试跑步** 细分 |
| DSPy / GEPA | 用反馈改写指令,小模型追上大模型 | 优化对象应是 **`.mq.md` 提示文档 / standing / 路由策略文件**,不是黑盒字符串 |
| 工作流编译进权重 | 程序化流程进小模型权重,上下文常数级 | 长期对应「高频 OKF 技能 → 专用小模型」;短期优先 **llm_free 源码路径** |
### 2.3 安全:技能不可信 + 沙盒必验
恶意技能基准与 SoK 均强调:**技能说明与代码默认不可信**,须运行时隔离。Marqdo 新沙盒(默认拒 plugin/net/exec)正好是技能晋升前的证明场。
---
## 3. Marqdo 已有资产(优化起点)
| 资产 | 现状 | 优化杠杆 |
|------|------|----------|
| 代码即文档 | `.mq.md` = 程序 = 提示工作面;GFM 表 / 链接取元 | 减少 json 胶水;让模型「看见」结构 |
| 写回 | `marqdo-out` 槽;step 默认写回 | 晋升证据、失败避坑 |
| OKF / agent-kb | 命中 / near / promote / solidify / `llm_free` | 复用率、降本主轴 |
| EKC / EFI | L0–L4 catalog;preflight REUSE/ADAPT/CREATE | 生成前先查工程知识 |
| Adaptive routing | marqdo / small-llm / llm / auto + policy 文件 | 再细分 sandbox 试跑 vs 开放推理 |
| Sandbox | CoW + capped `run`;`ext/ai/sandbox` | **试跑闸门**;未 commit 不污染仓库 |
| MCP / corpus | 证据工具,`authority=workbook` | 保持不升权威 |
---
## 4. 问题分析(差距,不是功能羡慕)
### P1 — 试跑与晋升未焊死
沙盒已能 CoW 试跑,但 **`agent.step` / `plan` 默认仍可直接改真实树**;OKF `llm_free` 晋升不强制「沙盒金样绿」。
→ 风险:未验证技能进入复用池(业界 ForgeAgent / MalSkillBench 已证明此问题)。
### P2 — 技能形态双轨
Anthropic Skills = 文件夹 + 渐进披露;Marqdo = 可执行 `.mq.md` + OKF 类型。
→ 机会:用 **OKF frontmatter + 可执行体** 统一,不必引入第二套 SKILL.md 权威;缺的是 **披露层级与验证元数据**(适用条件、fixture、sandbox profile)。
### P3 — 路由粒度偏粗
现有路由偏「整任务后端」;未区分:查 OKF / 写补丁 / 沙盒 `run` / 对外 HTTP。
→ Switchcraft 启示:按 **步骤类型** 选模型,且「便宜模型推理 token 爆炸」要计入总成本。
### P4 — 评测未锁差异化
Wave B1 仍 Active:缺稳定 **Skill Lift / 沙盒证明率 / llm_free 命中率 / 文档可读性** 指标。
→ 没有指标,优化会滑回「多调几次模型」。
### P5 — 代码即文档在 Agent 产出侧仍易腐化
模型仍可能吐 `json.set` 链、混用 EN/ZH API、跳过表结构。
→ 沙盒可跑通语法,但 **风格门禁**(lint / preflight)未默认卡在 commit 前。
### P6 — 上下文与 EKC 未默认进每步
EFI / catalog 能力在,但 step 默认上下文仍可能偏源码切片,缺少「先 REUSE」硬门槛。
### P7 — LLM 表面与 Agent 成本账未统一
`llm.ask` / `stream` / usage 已有;Agent 侧缺 **按会话/技能的成本仪表盘** 写回文档(可 git 审)。
---
## 5. 优化目标函数(建议)
在固定任务集上最大化:
\[
\begin{align*}
& \text{ReuseRate}(\text{OKF hit} + \text{llm\_free}) \\
&+ \text{SandboxProofRate}(\text{试跑绿再 commit/promote}) \\
&- \lambda_1 \cdot \text{TokenCost} - \lambda_2 \cdot \text{HostMutationsWithoutCommit}
\end{align*}
\]
约束:权威真相仍是 `.mq.md`;不引入隐藏 TOOL 主循环;不改 `doc/next/*`。
---
## 6. 外部资料索引(抽样)
| 类型 | 链接 |
|------|------|
| Skills | [Anthropic engineering: Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) · [Claude Code skills](https://code.claude.com/docs/en/skills) · [agentskills / anthropics/skills](https://github.com/anthropics/skills) |
| 论文 | [SoK: Agentic Skills](https://arxiv.org/html/2602.20867) · [Skill Issue (repo SKILL 优化)](https://arxiv.org/html/2609.12742v1) · [ACES Skill Lift](https://arxiv.org/html/2608.20614) · [MalSkillBench](https://arxiv.org/html/2606.07131v3) · [Compiling workflows into weights](https://arxiv.org/html/2605.22502) |
| 开源/产品 | [ForgeAgent](https://github.com/Yashasm18/ForgeAgent) · [DSPy GEPA](https://dspy.ai/current/getting-started/gepa-optimization/) · [Switchcraft](https://www.microsoft.com/en-us/research/publication/switchcraft-ai-model-router-for-agentic-tool-calling/) |
---
## 7. 结语
Marqdo 不缺「再一个 Agent SDK」;缺的是把 **文档真相、知识晋升、沙盒证明、模型路由** 收成可度量闭环。下一篇方案文档按问题编号给出可选方向与推荐波次,**不预设唯一银弹**。
+392
View File
@@ -0,0 +1,392 @@
# 调研:AI 扩展库沙盒设计(执行隔离 × 工作区暂存 × 写回)
| | |
|---|---|
| 状态 | **调研笔记 · 供 `ext/ai/*` 沙盒设计锁定参考**(**2026-10-16 修订**:纳入「AI 只生成 Marqdo」产品约束) |
| 日期 | 2026-10-16 |
| 范围 | 浏览器 WASM / WASI、OS 进程沙盒、容器 / microVM、CoW 叠加工作区、符号链接暂存方案;对照 Marqdo AI 栈 |
| 相关设计 | **[ext-ai-sandbox.md](../design/ext-ai-sandbox.md)** · **[roadmap/ext-ai-sandbox.md](../roadmap/ext-ai-sandbox.md)** · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [stdlib-writeback.md](../design/stdlib-writeback.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [adr/0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) · [ai-stack.md](../roadmap/ai-stack.md) · [ext-abi.md](../design/ext-abi.md) · [stdlib-modules.md](../design/stdlib-modules.md) |
| 姊妹调研 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) · [ai-agent-llm-optimize-2026-10.md](ai-agent-llm-optimize-2026-10.md) · [ext-ai-optimize.md](../design/ext-ai-optimize.md) |
---
## 0. 一句话结论
**在「Agent 只生成 / 只执行 Marqdo(`.mq.md`)」这一产品约束下,Marqdo AI 沙盒应以 Wasm 为主沙盒——且必须是「内核 + `lib/*` + `ext/*`」可运行的完整运行时沙盒,而不是只跑光秃解释器。**
锁定方向:
1. **执行隔离 = Marqdo Wasm 运行时(与 ADR 0002 同构)** — deny-by-default 能力导入;**默认不授予** shell / 外联 / `dlopen` 原生插件。AI 产出面收窄到 Markdown 程序后,不必为通用 coding Agent 的「任意二进制」付沙盒税。
2. **库完备性是验收线,不是加分项** — 沙盒内须能 `import lib/…` 与受支持的 `ext/…`;缺能力时 **显式失败**,禁止静默空成功(对齐 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5)。
3. **工作区突变 = CoW / whiteout / 显式 commit**(应用层 VFS,必要时 overlay)— 「修改短暂不生效 → 确认写回」保留;**禁止以符号链接森林作为隔离边界**。
4. **OS 沙盒 / microVM** — 降为 **逃逸舱 / 托管 Profile**:仅当显式启用 foreign、`subtask` 真子进程、或未来多租户托管时使用;**不是** Marqdo-only Agent 的默认主路径。
初稿曾按「通用 coding Agent 还需 shell」把 Wasm 与 bwrap 并列;在 Marqdo-only 约束下,主结论改为 **Wasm-first + 库完备 + CoW 写回**。
---
## 1. 调研方法与边界
### 1.1 做了什么
| 动作 | 说明 |
|------|------|
| 厂商/产品文档 | Anthropic Claude Code sandbox / `@anthropic-ai/sandbox-runtime`;VS Code Copilot agent sandboxing;Docker AI Sandboxes;Turso AgentFS CoW overlay;OpenSandbox isolation sessions;WASI / jco preview2-shim;VS Code for the Web WASM webshell |
| 工程对比文 | Northflank / Cosmonic 2026 agent sandbox 指南;gVisor vs Firecracker vs Docker 对比;ContainAI security comparison |
| 学术与标准 | USENIX SEC'22 *Provably-Safe Multilingual Software Sandboxing using WebAssembly*;KTH 论文 *Intra-process Fault Isolation Using WebAssembly*(SFI 通信开销);ACM TOSEM *Research on WebAssembly Runtimes: A Survey*(2025);WASI Design Principles(capability / 无 ambient authority) |
| 安全案例 | brig 项目挂载 symlink 逃逸(CVSS 8.2);Anthropic sandbox-runtime 对 bwrap bind 跟随 symlink 的修复;Docker Sandbox「direct mount vs clone」威胁说明 |
| 对照本仓 | `ext/ai/{llm,agent}`、`lib/writeback`、`lib/subtask`、ADR 0002 浏览器 WASM、`RunOptions.allow_fs_write` 默认关 |
### 1.2 不做的
- 不把「发版用的容器镜像」与「Agent 工具沙盒」混为一谈。
- 不宣称某一云厂商托管沙盒(E2B / Modal / Daytona)为 Marqdo 默认依赖。
- 不修改 `doc/next/*`(手写真相源);本文件只进 `doc/research/`。
### 1.3 产品约束(修订要点):AI 只生成 Marqdo
这是相对通用 coding Agent(Claude Code / Codex)的 **结构性好消息**:
| 通用 Agent | Marqdo AI Agent(本调研采纳) |
|------------|------------------------------|
| 模型可产出 shell / Python / 任意仓库补丁 | 模型产出面收束为 **`.mq.md`(文档即程序)** |
| 沙盒必须兼容「整台开发机能力」 | 沙盒只需跑 **同构 Marqdo 运行时** |
| Wasm 往往只能罩住工具子集 | Wasm **可以**成为主执行边界 |
| 标准库 = 语言运行时 + OS 工具链 | 标准库 / 扩展 = **`lib/*.mq.md` + `ext/**`(+ 受控宿主能力)** |
硬规则建议(后续 design 应写死):
1. Agent 工具表 **不提供** 通用 `bash` / 任意语言 `exec`(除非显式 opt-in 逃逸舱,且另套 OS 沙盒)。
2. Agent 改仓库的权威动作是 **写 / 修订 `.mq.md`(含写回块)**,经 CoW 会话再 `commit`。
3. 运行 Agent 生成的程序 = 在沙盒里 `run` 该 `.mq.md`,且其 `import` 的 **lib 与 ext 必须可用或显式报不可用**。
### 1.4 威胁模型(在 Marqdo-only 下收窄)
| 威胁 | 典型路径 | Marqdo-only 下的权重 |
|------|----------|----------------------|
| T1 提示注入 | 诱导读密钥、外泄、破坏 `.mq.md` | 仍高 — 靠能力拒绝 + CoW |
| T2 工具侧信道 | `subtask`/`foreign` 子进程 | **默认关闭**;opt-in 才升权 |
| T3 工作区即时破坏 | 直接写穿源树 | 靠 CoW;commit 闸门 |
| T4 挂载逃逸 | symlink / bind 打穿 | 仍相关 — **勿用 symlink 作 W 层** |
| T5 网络外泄 | `lib/net` / llm 出站 | 能力开关 + 域名策略 |
| T6 Wasm 宿主桥过宽 | `host_fs_*` / 插件桥过宽 | **主威胁** — 桥 = 权限表 |
| T7 库残缺假安全 | 沙盒能跑 `# main` 但 `import lib/fs` 怪崩或静默空 | **产品验收威胁** |
**成功标准:** 失败域止于会话 upper + 已授予能力;真实工作区默认只读直至 commit;**代表性 `lib/*` 与 `ext/*` 金样在沙盒内可跑或得到明确 `unavailable in sandbox` 诊断**。
---
## 2. 先拆三个「沙盒放哪里」(Marqdo-only 版)
业界「Harness / Workspace / Execution」三分法仍成立,但 **Execution 的内容变了**:
```text
┌──────────────────────────────────────────────────────────┐
│ Pattern H — Harness(编排环) │
│ ext/ai/agent · parent Plan-and-Move ·(可选)MCP client │
├──────────────────────────────────────────────────────────┤
│ Pattern W — Workspace mutation(.mq.md 真相如何变) │
│ CoW upper / whiteout / diff / commit → writeback │
├──────────────────────────────────────────────────────────┤
│ Pattern X — 执行 Agent 产出的 Marqdo 程序 │
│ Wasm Marqdo runtime + embedded/packaged lib + sandboxed │
│ ext 能力面(非「任意 shell」) │
└──────────────────────────────────────────────────────────┘
```
| Pattern | Marqdo 落点 | 沙盒要解决什么 |
|---------|-------------|----------------|
| H | `ext/ai/agent` | 编排是否持有过宽宿主权限;模型 I/O 与执行隔离 |
| W | `lib/writeback` · 工作簿 | 编辑是否立刻污染仓库;人审/父裁决后落盘 |
| X | **Wasm 内 `run` `.mq.md`** | 计算隔离;**lib/ext 能力是否完备且受控** |
用户提案在 Marqdo-only 下:**Wasm 作 X 主底层是正确方向**;仍须改掉 symlink,并补上 **库完备性** 这一环。
---
## 3. 方案谱系(横向对比)
> **读法(修订后):** 下表仍保留通用 Agent 对照。对 **Marqdo-only** 产品,请以 §0 / §5 / §6 的 Wasm-first 结论为准;本节 A/B 升权,F/G/H 降为逃逸舱或托管。
评分:● 强 / ◐ 中 / ○ 弱 / — 不适用。维度按「隔离强度」等客观属性;**产品适配**见 §5。
| 方案 | 隔离强度 | 启动成本 | 任意二进制 | 工作区暂存语义 | 与 Marqdo 契合 | 主要风险 |
|------|----------|----------|------------|----------------|----------------|----------|
| **A. 浏览器 WASM + 虚拟 FS** | ●(计算)◐(经桥的 FS) | ● | ○ | ◐(需自建 overlay) | ●(已有 ADR 0002) | 宿主桥过宽;无原生 toolchain |
| **B. WASI / Component Model(非浏览器亦可)** | ● | ● | ○(仅 WASI 目标) | ●(preopens + 自建 VFS) | ● | 工具链不全则需降级 |
| **C. 符号链接映射工作区 + 延迟写回** | ○ | ● | —(本身不是执行沙盒) | ◐(似是而非) | ○ | **symlink 逃逸是已知高危类** |
| **D. 应用层 CoW VFS(upper/lower/whiteout)** | ◐(逻辑) | ● | — | ● | ●● | 必须配合 X 层 OS 隔离 |
| **E. OS overlayfs / FUSE / AgentFS 式 CoW** | ●(配合命名空间) | ◐ | ●(在沙盒内) | ●● | ● | Linux/macOS 实现分叉;运维 |
| **F. bubblewrap / Seatbelt(Anthropic SRT 类)** | ● | ● | ● | ○(默认可写 cwd) | ● | 需另加 CoW 才有「暂不生效」 |
| **G. Docker / 硬化容器 / gVisor** | ◐→● | ◐ | ● | ◐(volume 策略) | ◐ | 共享内核或兼容性;重 |
| **H. microVM(Firecracker / Kata)** | ●● | ◐ | ● | ◐ | ○(本地 CLI 过重) | KVM/运维;适合多租户托管 |
| **I. 纯语言沙盒(RestrictedPython 等)** | ○ | ● | ○ | — | ○ | 对 Agent 工具链几乎无用 |
### 3.1 A — 浏览器 WASM + 虚拟 FS
**机制:** Wasm 线性内存 + 校验 + 仅经 import 碰宿主;FS 多为内存树 / OPFS / 经 JS bridge 的映射。Marqdo 已锁定「解释器进 WASM」(ADR 0002),默认 `allow_fs_write=false`。
**文献支撑:** Wasm 作为 SFI 窄腰(Bosamiya et al., USENIX SEC'22);进程内沙盒跨边界通信可比 IPC 快数量级(KTH Wasm-SFI 论文);WASI 明确 **capability / 无 ambient authority**。
**优点:** 与「代码即文档」浏览器运行同构;deny-by-default;适合跑 `.mq.md`、公式库、受控插件。
**缺点:** 不能原生跑 `cargo test` / `npm` / 任意 shell;安全上限取决于 **bridge 授予了什么**;浏览器场景下「符号链接用户工作区」通常要落到 File System Access API 或服务端中继,**不是** POSIX symlink 语义。
**判定:** 在 **Marqdo-only** 约束下,作为 **Pattern X 主沙盒** 与浏览器内 Marqdo 的正解;完备性取决于 **lib 嵌入 + ext 能力桥**(§4.1),不取决于 shell。通用「任意二进制 Agent」场景下仍不够——但那不是本产品默认。
### 3.2 B — WASI / Component Model(CLI 宿主)
**机制:** preopens 显式挂载;`WASIShim({ sandbox: { preopens, enableNetwork: false } })`(Bytecode Alliance jco);Component imports = 权限表。
**优点:** 与 Wasm 同族,可在 Node/Wasmtime 跑,不绑浏览器;能力模型清晰。
**缺点:** 同 A,任意 Linux 工具链需「宿主机再包一层」或改编译目标。
**判定:** Marqdo **官方扩展 / 插件中可 Wasm 化的部分**应走这条;与 ADR 0002 一条能力谱。
### 3.3 C — 符号链接映射工作区(用户设想的核心)
**设想:** 沙盒根下用 symlink 指向用户文件;写改暂存别处;确认后写回;删除 = 删 symlink。
**表面吸引力:** 零拷贝读、实现「像」有暂存。
**为何行业不把它当隔离原语:**
1. **Bind/mount 跟随 symlink 是经典逃逸。** Anthropic `sandbox-runtime` 明确修复:`allowWrite` 若为指向界外的 symlink,bwrap `--bind` 会把真实目标变成可写(PR #138 类修复)。
2. **项目挂载未解析 symlink 可致高危。** Endor Labs 披露 brig「project mount symlink traversal」(CVSS 8.2):Agent 在可写项目内把子目录换成指向 `/etc` 的 symlink,下一轮宿主机按字符串挂载即打穿。
3. **「删除 = 删 symlink」语义错误。** 删链接只去掉别名,**不等于**对 lower 层文件的 whiteout;若链接指向真实文件且曾被打开写穿,删除链接也救不回。
4. **写穿风险。** 若某路径被解析成真实 inode 且可写,暂存承诺立刻破产。
5. **跨平台。** Windows junction/reparse、浏览器虚拟 FS、容器 bind,行为不一致。
**判定:** **否决作为 Marqdo 默认工作区隔离方案。** 允许在 **只读、已解析、拒绝可写路径上的 symlink 组件** 的前提下作实现细节,但不得当作安全边界叙事。
### 3.4 D — 应用层 CoW VFS(推荐作 W 层默认)
**机制:**
```text
lower = 真实工作区(只读打开 / 只读能力)
upper = 会话 delta(内存 map / 目录树 / SQLite blob)
whiteout = 逻辑删除集合
view(path) = upper ?? (!whiteout && lower)
commit() = 把 upper/whiteout 应用到 lower(可经人审)
discard() = 丢弃会话
diff() = 可审变更集
```
与 Turso AgentFS、OpenSandbox `workspace.mode: overlay` 的 **语义同构**,但不强制 FUSE。
**与 Marqdo 对齐点:**
| VFS 操作 | Marqdo 真相 |
|----------|-------------|
| `diff()` | 父 Agent / 人审材料;可进 view |
| `commit()` 文本结果 | `writeback.record` / 工作簿补丁 |
| `discard()` | 失败回合不污染仓库 |
| 只读 lower | 防止 T3 即时破坏 |
**优点:** 纯用户态、可测、可嵌入 `plugins/agent`;不依赖 root/FUSE;金样可锁。
**缺点:** 对 **沙盒内原生工具**(它们走真实 POSIX)不可见,除非再挂 E 或把工具 I/O 也改走 VFS API。
**判定:** **Pattern W 的默认实现。**
### 3.5 E — OS CoW overlay(AgentFS / overlayfs / OpenSandbox)
**机制(AgentFS 公开设计):** lower=宿主只读;upper=SQLite delta;删除=whiteout;Linux 用 FUSE+user/mount ns;macOS 用 NFS+`sandbox-exec`。OpenSandbox 默认 `overlay`,会话结束可丢 upper。
**优点:** 对 **任意 shell 工具**透明;「改了但宿主机 `git status` 仍干净」体验业界已验证。
**缺点:** 平台依赖;FUSE 权限;与应用层 D 双实现成本。
**判定:** **当 Pattern X 需要真实 shell 且要求暂存对工具透明时**启用(Linux 优先);作为 D 的「native 加速后端」,不是替代 Wasm。
### 3.6 F — OS 进程沙盒(bwrap / Seatbelt / VS Code Copilot)
**机制:** Anthropic:文件系统隔离 + **网络隔离(缺一不可)**;Linux bubblewrap + 代理;macOS Seatbelt。VS Code Copilot:同类依赖;路径分 readwrite / readonly / denied;明确「不是 VM,削弱授权即削弱边界」。
**优点:** 本地编码 Agent 的事实标准;覆盖子进程;启动轻。
**缺点:** 默认可写 cwd → **没有**「暂不生效」;必须与 D/E 组合。Symlink 配置路径需解析与拒绝。
**判定:** **Pattern X(shell/外联/MCP)本地默认。**
### 3.7 G / H — 容器与 microVM
**共识:** 裸 Docker 共享内核,不适合作唯一边界应对不可信代码;gVisor 加强 syscall 拦截;Firecracker/Kata 适合多租户与高威胁(~125ms 级启动)。Docker AI Sandboxes 区分 **direct mount(即时写穿)** vs **clone(只读源 + 私有副本)**——后者才接近「确认后写回」。
**判定:** Marqdo **本地 CLI 默认不强制 microVM**;若未来 `ext` 提供托管执行 / 多租户,再把 H 定为服务端 Profile。G 可作为打包/CI Profile。
### 3.8 I — 语言级沙盒
对「Agent 会跑 shell」场景基本无效;仅作极窄解释器内嵌参考。
---
## 4. 专门评估:用户提案(修订)
> 浏览器 WASM 作沙盒底层 + 符号链接用户工作区 + 修改短暂不生效 + 确认后写回 + 删除变删 symlink。
> **补充约束:** AI 只生成 Marqdo;沙盒须能用标准库与扩展库。
| 子命题 | 评价 | 说明 |
|--------|------|------|
| Wasm 作主执行隔离 | **在 Marqdo-only 下正确** | 与 ADR 0002 同构;不必为 shell 全集付税 |
| 沙盒须含 lib + ext | **正确且关键** | 「能跑 `# main`」≠ 好沙盒;见 §4.1 |
| 「短暂不生效」 | **正确** | CoW / staging(方案 D,必要时 E) |
| 「确认后写回」 | **正确且极契合 Marqdo** | 与 writeback、父裁决、workbook 同一哲学 |
| 「symlink 映射工作区」 | **仍错误** | 与是否只用 Marqdo 无关;换 CoW/whiteout |
| 「删除 = 删 symlink」 | **仍错误** | 应为 whiteout;commit 时再对 lower 删除 |
| 「性能最好且安全性最高」 | **Wasm 主路径下接近成立** | 前提是桥最小权限 + CoW;symlink 仍拉低安全 |
**修订后的正确表述:**
> **以 Wasm Marqdo 运行时为主沙盒,打包/嵌入 `lib/*`,经能力桥提供受支持的 `ext/*`;工作区用 lower 只读 + upper/whiteout;人审/父裁决后 commit。符号链接不作隔离原语。shell/外联/原生 dlopen 默认关闭,仅作显式逃逸舱。**
### 4.1 库完备性:什么叫「标准库和扩展库也能用」
沙盒若只能跑内置算术、却不能 `import lib/json` 或跑 `ext/ai/llm` 的离线金样,对 Agent 开发几乎无用——模型生成的 `.mq.md` **本来就会依赖 lib/ext**。
三类库进沙盒的路径不同:
| 类别 | 今日形态 | 沙盒策略 |
|------|----------|----------|
| **纯 `.mq.md` 库**(多数 `lib/*`、部分 `ext` 门面) | 源码 import | **嵌入或会话导入图**(已有 `embedded_lib` / import map)— 必须默认可用 |
| **需宿主能力的 lib**(`fs` / `net` / `writeback` / `subtask` / `datetime.now`…) | `host_*` | **经能力表桥接**到会话 VFS / 受控 clock / 受控 fetch;默认最小集 |
| **原生 ABI 扩展**(`plugins/web`、`plugins/agent`、quantum 等 `.so`) | `plugin.load` + dlopen | 浏览器/Wasm **无 dlopen**(ADR 0002 N2)。沙盒内应:**纯 mq 门面 + Wasm 插件**、或 **宿主代执行且权限计入会话**、或 **显式 `unavailable`** — 禁止假装成功 |
与 [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) §5 对齐并扩展为 **Agent 沙盒能力矩阵(草案)**:
| 能力 | 沙盒默认 | 备注 |
|------|----------|------|
| builtins / 表 / 控制流 / 对象 | ✓ | 内核 |
| `lib/math` `json` `table` `text` `collection`… | ✓ | embedded |
| `lib/fs` | ✓(仅会话 VFS) | 写进 upper;禁越出 root |
| `lib/writeback` | ✓(写会话内 `.mq.md`) | commit 后才进真实树 |
| `lib/net` / llm HTTP | 默认关 / 域名白名单 | 与 T5 |
| `lib/subtask` `fn=` | ✓(同 Wasm 会话) | |
| `lib/subtask` `path=`/`code=`/`lang=` | **默认拒** | 逃逸舱 + OS 沙盒 |
| `lib/plugin` + 原生 `.so` | **默认拒** | 改 Wasm 插件或宿主代执行 |
| `ext/ai/llm` · `ext/ai/agent`(mq 门面) | ✓(能力允许时) | 网络/密钥另授 |
| `ext/web` 服务端 listen/DB | **默认拒或只读 stub** | 完整 axum 不进沙盒;可测「装配/渲染」子集 |
| `ext/quantum` / `ext/linalg` | 目标 ✓ | 优先纯逻辑 / Wasm 插件,避免强依赖宿主机 .so |
**验收金样建议(S 阶段):**
一套「沙盒烟囱」:`import` 常用 lib → 写会话文件 → writeback → `diff` → `commit`;再各挑一个 **纯逻辑 ext** 与一个 **需网络的 ext**(后者验证拒绝/白名单)。缺能力必须诊断含 `unavailable in sandbox`(或同等措辞)。
---
## 5. 综合评分(面向 Marqdo-only 产品)
加权(修订):执行隔离契合 Marqdo-only 30%、**lib/ext 完备** 25%、与 writeback 真相 20%、实现成本 15%、跨端(CLI↔浏览器)10%。
(「任意 shell 工具完备」不再作为主权重。)
| 候选架构 | 分(相对) | 备注 |
|----------|------------|------|
| **A/B Wasm-first + D CoW + 库完备能力表** | **100(推荐)** | 主路径 |
| 同上 + 逃逸舱 F(opt-in shell) | 95 | 兼容少数 foreign 需求 |
| D + E + F(通用 coding 向) | 75 | 过重;非 Marqdo-only 默认 |
| 仅 F(可写 cwd) | 55 | 缺 CoW;且鼓励非 mq 工具 |
| 仅 A 但无 CoW、无 lib 嵌入 | 40 | 「半沙盒」 |
| 仅 C(symlink) | 20 | 否决 |
| 仅 H(人人 microVM) | 50 | 托管可选;本地默认过重 |
**绝对「最硬」单点**仍可以是 microVM(托管 Profile)。
**Marqdo「最合适」:** **Wasm 完整运行时沙盒(内核+lib+受控 ext)+ CoW 工作区 + commit 闸门**。
---
## 6. Marqdo 应采用的沙盒设计(推荐锁定草案 · 修订)
### 6.1 产品形态
| Profile | 场景 | 执行(X) | 工作区(W) |
|---------|------|-----------|------------|
| **`mq-sandbox`(默认)** | Agent 生成并试跑 `.mq.md` | **Wasm Marqdo** + embedded `lib/*` + 能力桥 `ext` | 应用层 CoW;commit→真实树 / writeback |
| **`browser`** | 页内同构运行 | 同左(ADR 0002) | 内存/OPFS;无 POSIX symlink |
| **`escape`(显式)** | foreign / 真子进程 | OS 沙盒包一层 | 仍建议 CoW 可见 |
| **`hosted`(可选)** | 多租户 | Wasm 或 microVM | 会话隔离;凭证外置 |
### 6.2 推荐架构图
```text
┌──────────────────────────────────────┐
│ ext/ai/agent (Harness) │
│ 只产出 / 编排 .mq.md · 人审闸门 │
└──────────────────┬───────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼
┌────────────────────┐ ┌────────────────────┐
│ Workspace CoW (W) │ │ Marqdo Wasm (X) │
│ lower = RO 工作区 │◄── fs/writeback ───│ 同构解释器/VM │
│ upper / whiteout │ 能力导入 │ + embedded lib/* │
│ diff·commit·discard│ │ + ext 能力面 │
└─────────┬──────────┘ │ 默认: 无 shell/so │
│ └────────────────────┘
▼
真实工作区 / <!-- marqdo-out -->
(代码即文档真相源)
(可选)escape: subtask path|code|lang → OS sandbox
```
### 6.3 API 面建议(设计级,非立即实现)
落点倾向:宿主能力进 `plugins/agent` / Wasm HostContext;作者面经 `ext/ai` 或 `lib`(**禁止** `ext/**` 直调 `host_*`)。
| 概念 | 语义 |
|------|------|
| `sandbox.open(root, mode=cow)` | 打开会话;lower 只读 |
| `sandbox.read/write/list/remove` | 经 view;remove → whiteout |
| `sandbox.diff` / `stat` | 供父 Agent / view |
| `sandbox.commit` / `discard` | 闸门;可要求 HITL |
| `sandbox.run(source\|path, caps=…)` | **Wasm 跑 Marqdo**;caps 声明 fs/net/llm/… |
| `sandbox.caps` / `inspect` | 列出已授能力与 lib/ext 可用性(对齐 `web.inspect` 哲学) |
| `sandbox.exec(...)` | **仅 escape Profile**;默认不存在于作者工具表 |
与现有衔接:
- `lib/*`:优先 embedded;FS/时间/网络走会话 caps。
- `ext/*`:mq 门面可加载;原生插件默认不可用并诊断;长期可 Wasm 化的(linalg/quantum 逻辑)优先进 Wasm。
- `lib/writeback`:写入会话内文件;`commit` 时进入真实树。
- `lib/subtask`:默认仅 `fn=`;`path`/`code`/`lang` 要 escape。
### 6.4 硬禁(写入后续 design 时应保留)
1. **不以 symlink 森林作为隔离或暂存原语。**
2. **不以「能跑空 `# main`」宣称沙盒完成** — 必须过 lib/ext 完备金样或显式 unavailable。
3. **默认工具表不提供通用 shell / 任意语言 exec。**
4. **不默认可写 bind 真实工作区。**
5. **宿主桥 = 权限表**:未授能力不得 ambient 成功。
6. **不静默降级**:缺 Wasm/能力时不得假装已隔离。
7. **`ext/**` 不调 `host_*`**(既有宪法)。
### 6.5 分阶段落地(建议,非 `doc/next`)
| 阶段 | 交付 | 验收线索 |
|------|------|----------|
| S0 | 威胁模型 + 本调研(含 Marqdo-only) | 本文 |
| S1 | Wasm `run` + embedded 核心 `lib/*` + 会话 VFS 读 | 常用 lib 金样在沙盒绿 |
| S2 | CoW upper/whiteout + diff/commit/discard | 未 commit 时宿主机 `git status` 干净 |
| S3 | writeback / 工作簿在会话内可写;commit 对齐 | agent step 金样 |
| S4 | caps:net/llm 白名单;`subtask` 非 fn 默认拒 | 诊断字符串稳定 |
| S5 | 代表性 ext(纯逻辑 + 需网)沙盒金样 | 完备性验收 |
| S6 | (可选)escape OS 沙盒;hosted microVM | 文档标明非默认 |
---
## 7. 外部资料索引(抽样)
| 类型 | 引用 |
|------|------|
| 产品 | [Anthropic: Claude Code sandboxing](https://www.anthropic.com/engineering/claude-code-sandboxing) · [sandbox-runtime](https://github.com/anthropic-experimental/sandbox-runtime) · [VS Code agent sandboxing](https://code.visualstudio.com/docs/agents/run/agent-sandboxing) · [Docker AI Sandboxes security](https://docs.docker.com/ai/sandboxes/security/) · [Turso AgentFS overlay](https://turso.tech/blog/agentfs-overlay) · [OpenSandbox isolation sessions](https://open-sandbox.ai/guides/isolation-sessions) |
| 标准 | [WASI Design Principles](https://github.com/WebAssembly/WASI/blob/main/docs/DesignPrinciples.md) · [jco preview2-shim sandbox](https://github.com/bytecodealliance/jco/blob/main/packages/preview2-shim/README.md) |
| 论文 | Bosamiya et al., *Provably-Safe Multilingual Software Sandboxing using WebAssembly*, USENIX Security 2022 · *Intra-process Fault Isolation Using WebAssembly* (KTH) · *Research on WebAssembly Runtimes: A Survey*, ACM TOSEM 2025 |
| 综述 | [Cosmonic: Choosing an AI agent sandbox (2026)](https://cosmonic.com/ai-sandbox/choosing-an-agent-sandbox/) · [Northflank: MicroVMs, gVisor & isolation](https://northflank.com/blog/how-to-sandbox-ai-agents) |
| 安全案例 | [brig symlink traversal / Endor Labs](https://www.endorlabs.com/learn/project-mount-symlink-traversal-in-brig-how-a-sandbox-reaches-host-directories-it-was-never-given) · Anthropic sandbox-runtime symlink bind 修复 |
---
## 8. 结语
- **产品好消息:** Agent 只生成 Marqdo → **Wasm 主沙盒设计成立**,不必默认扛通用 shell Agent 的复杂度。
- **好沙盒的定义:** 不只跑内核,还要 **`lib/*` 可用、`ext/*` 在能力表内可用或显式不可用**;再加 **CoW + commit** 保护仓库真相。
- **仍要改掉的:** 符号链接当暂存/隔离;默认开放 foreign/dlopen;「空 main 能跑」就算完工。
- **降级为非默认的:** bwrap/microVM — 留给 escape / hosted,而不是 Marqdo-only 主路径。
不急着实现。下一步若继续收敛,再开 `doc/design/ext-ai-sandbox.md` 把 **能力矩阵 + 库完备金样清单** 锁死即可;**仍不要改 `doc/next/*`**。
+290
View File
@@ -0,0 +1,290 @@
# 外联内核 · 文档会话 · 决策记录
| | |
|---|---|
| 状态 | **Decided(由用户授权代为拍板)** |
| 日期 | 2026-10-17 |
| 范围 | 外联库(`lib/foreign`)· 外联内核 · 文档会话 · view notebook 交互 |
| 相关 | [foreign-kernel.md](../design/foreign-kernel.md) · [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-v2.md](../roadmap/foreign-v2.md) · [notebook-session.md](../roadmap/notebook-session.md) |
| 核心表面 Δ | **无**——不新增 Markdown 标记;只使用既有 `#` / `##` / 表格 / 反引号 |
> 本文件记录「为什么这样设计」。实现细节分别落在设计文档与路线图中;本文件不重复 API 表。
---
## 0. 背景与授权
用户的核心诉求:
1. Marqdo 的本质是 **代码即文档、文档即知识库**;`.mq.md` 天生兼容 Markdown / OKF 知识库。
2. 外联库的初衷是**对标 Jupyter**:让文档与代码并行有用;但 Jupyter 有 Git 难跟踪、隐藏状态、execution_count 噪声等问题,Marqdo 要解决并超越。
3. `view` 模式天然适合这种交互(已有执行按钮、结构视图、writeback、trace)。
4. 之前外联库功能太单一;接下来必须支持:
- 多个代码块共享外联状态;
- 单步执行;
- 切换哪些外联内核共享状态;
- Marqdo 的状态/变量被外联使用;
- 外联的状态/变量被 Marqdo 使用。
5. 用户要求:**安全第一、效果最好、功能最强悍、不降级**;充分测试;每份讨论落成详细文档;文档提交并推送后再开发。
6. 用户强调:**设计语法不要用代码思维**,语法要天然可读。
本文档 = 对该授权的决策记录。后续实现若与本文冲突,先改本文并说明理由。
---
## 1. 关键结论
### 结论 A:外联库不是“跑 Python 的函数”,而是多语言内核运行时
`lib/foreign` 的定位升级为:
> **文档运行时与外部语言运行时之间的内核/会话层**:启动内核、执行代码单元、持久化状态、双向类型桥、生命周期与安全。
它不等同于 `subtask`(一次性并发任务),也不等同于 `writeback`(输出持久化)。
### 结论 B:Jupyter 级体验需要两层,不是一层
| 层 | 名称 | 责任 |
|---|---|---|
| **F** | Foreign Kernel Runtime | 内核进程、语言发现/注册、JSON 桥、会话、安全、记录 |
| **D** | Document Session | 文档会话、cell index、kernel 分配、单步、状态面板、执行日志、view 交互 |
上一版 `foreign-v2` 只覆盖 F。共享状态 / 单步 / 切换内核属于 D。两层分开设计、分开验收。
### 结论 C:Hybrid 执行模型
- **Program mode(规范模式)**:`marqdo run` / CI / 可复现执行。文档是程序;外联通过显式 `foreign.session_*` / `call` 编排;结果可重复。
- **Notebook mode(交互模式)**:`view` 中按 cell 执行、单步、切换内核、查看状态。适合探索,不默认写入文档。
- 两者共享同一个内核运行时与同一套 cell 索引;Notebook mode 是 Program mode 的**交互镜头**,不是替代品。
理由:如果让 cell 执行取代文档程序语义,Marqdo 就退化成 Jupyter;如果只有 Program mode,就失去 Jupyter 的即时反馈。Hybrid 同时保留两者。
### 结论 D:命名内核;同内核共享,跨内核/跨语言显式传值
- 一个文档可以有多个命名内核:`py:分析`、`py:绘图`、`js:前端`。
- 同一内核的 cell 共享全局状态。
- 不同内核(即使同语言)默认隔离。
- 不同语言不共享进程内存;只能通过 JSON / 文件 / DB 显式交换。
- 默认每个文档、每种语言一个 `default` 内核;命名内核按需开启。
- 跨文档默认隔离;全局内核以后再做。
### 结论 E:三种单步,分阶段实现
| 单步 | 含义 | 版本 |
|---|---|---|
| **Cell step** | 执行下一个代码单元,状态保留 | v2 必做 |
| **Marqdo statement step** | 逐条执行 Marqdo 语句,查看变量 | v2 复用现有 debugger |
| **Foreign line step** | 进入 Python/Node 逐行 | v2 不做;后续接 DAP/pdb/debugpy |
- 外联 cell 在 statement step 中是原子操作。
- “Step into foreign” 是独立项目,不能混入首版。
### 结论 F:显式状态桥优先,不做隐式自动镜像
- 默认通过 `session_set` / `session_get` / `call input` / `call result` 交换,JSON 拷贝。
- 不默认把 Marqdo 变量自动注入 Python,也不默认把 Python 变量自动写回 Marqdo。
- 原因:命名冲突、Secret 泄漏、类型丢失、隐式状态、不可复现、大对象拷贝。
- 后续可选 `mirror=True`:只同步 `mq_` 前缀、白名单类型、按值拷贝,且默认关闭。
### 结论 G:不新增围栏元数据;用文档原生的“内核表 / 会话表”
- 拒绝 ` ```python kernel=分析 `、`name=`、YAML kernel 配置、魔法注释。
- 使用既有绑定表 + GFM 表格(放在 `# main` 体内,与 cell 同作用域):
- `内核表` / `kernels`
- `会话表` / `session`
- 表格是**声明**,不是自动执行;只有 Run / Step 触发。
- 解析器不变,核心表面零增长;view/session 读取这两个约定绑定。
理由:`kernel=` 是 IDE 配置思维,破坏“代码即文档”;绑定表是文档目录/执行计划,人可读、机器可解析,且不把文档拆成多个对象作用域。
### 结论 H:输出默认临时,writeback 显式;状态不写进 `.mq.md`
- Notebook mode 的输出默认只在 view 中显示,不修改文档。
- 需要持久化时显式 writeback(沿用 `<!-- marqdo-out … -->`),可 Git 跟踪、可忽略。
- 执行日志放 `.marqdo/sessions/…`(默认 git 忽略)。
- 不把 execution_count / kernel 状态 / base64 输出写进 `.mq.md`。
### 结论 I:首批会话语言 Python + Node
- Python:Jupyter 的主场景,优先支持。
- Node:v1 已有基础,且当前开发环境可用。
- 15 个语言预设继续用于**一次性执行**;R / Julia / Ruby 等的持久会话通过自定义 bootstrap 逐步加入,不阻塞首版。
### 结论 J:v2 不做“外联回调 Marqdo 函数”
- 状态/值双向:✅
- Marqdo 代码作为源码文本传给外联:✅(外联按自己的语言执行)
- 外联代码调用 Marqdo `##` 函数:❌ v2;后续做 callback RPC(控制通道 + 重入 + 死锁处理)。
- 原因:重入解释器、线程安全、死锁、安全面都远超首版范围;先把数据/状态桥做稳。
### 结论 K:安全与测试是一等公民
- 所有 spawn / probe / session 入口检查 `allow_exec`。
- 进程组超时清理;有界 IO;stdin 写线程;输出上限;并发上限。
- 每文档生命周期,关闭即 kill;跨文档不共享。
- 测试:node + bash 为最小环境主路径;python 条件覆盖;单元测试覆盖切分/模板/JSON;金样例覆盖记录/超时/会话/并行/状态桥。
---
## 2. 逐问逐答(保留原始讨论颗粒度)
### Q1:外联库是做什么的?
**答**:它是文档的多语言执行总线,负责:
1. 内核生命周期(启动/重启/中断/关闭/切换);
2. cell 执行(源码 → kernel → stdout/stderr/result);
3. 状态持久化(同一 kernel 的 cell 共享命名空间);
4. 类型桥(Marqdo Value ↔ JSON ↔ 语言对象);
5. 环境发现与配置(probe/register/venv/config);
6. 记录与安全(耗时、退出码、截断、cap、清理)。
它不负责:文档语法(Language)、UI 布局(Document)、知识目录(Catalog)。这些由相邻层提供。
### Q2:是否支持外联库共享状态?
**答**:支持,但严格分层:
- 同一 kernel:共享全局变量。
- 同一语言不同 kernel:隔离。
- 不同语言:不共享内存,只能显式传值。
- Marqdo ↔ kernel:显式桥。
- 跨文档:默认隔离。
### Q3:能否单步执行?
**答**:能,但要定义清楚:
- cell step:v2 做。
- Marqdo statement step:现有 debugger 已有,v2 接入 view。
- foreign line step:v2 不做;后续 DAP。
### Q4:能否切换哪几个外联库共享状态?
**答**:能,用命名内核:
- `py:分析` 下所有 cell 共享;
- `py:绘图` 隔离;
- 每个 cell 有 kernel 归属;
- 切换归属不迁移状态,需要重跑;
- 跨语言用显式桥。
### Q5:Marqdo 的代码/状态能否被外联使用?外联的状态/变量能否被 Marqdo 使用?
**答**:
- Marqdo 值 → 外联:`session_set` / `call input` / `session_eval input`;JSON 拷贝。
- 外联值 → Marqdo:`session_get` / `call` 返回值;赋值。
- Marqdo 代码 → 外联:作为源码文本传递;外联按自己的语言执行,不是 Marqdo 语义。
- 外联代码 → Marqdo 函数:v2 不做,后续 callback RPC。
- 自动镜像:v2 不做,后续可选。
### Q6:如何超越 Jupyter?
**答**:不是“功能更多”,而是把 Jupyter 的隐藏面变成显式面:
| Jupyter | Marqdo |
|---|---|
| `.ipynb` JSON 混入输出/execution_count | `.mq.md` 源码干净;输出可选 writeback |
| 隐藏 kernel 状态 | 内核 + 文档会话 + 状态面板 + journal |
| 一个 notebook 一个 kernel | 命名内核 + 每 cell 归属 + 显式桥 |
| 只有 cell step | cell step + statement step |
| 手动 Run All | restart & run all + dirty/stale + replay |
| 无知识目录 | OKF / catalog;cell 是可发现知识单元 |
---
## 3. 被拒绝的方案
| 方案 | 为什么拒绝 |
|---|---|
| 围栏元数据 ` ```python kernel=分析 ` | Language 层变更;需 ADR;把文档语法变成 IDE 配置;破坏可读性 |
| YAML `kernels:` 配置 | 代码思维;与“文档即知识”冲突;表格已能表达 |
| 魔法 HTML 注释 `<!-- kernel: 分析 -->` | 不可见、易漂移、读者不可见;违背可读性 |
| 自然语言 prose 解析(“把 xs 送给分析内核”) | 非确定性;误触发;违背“叙述默认安全” |
| 隐式自动镜像变量 | 命名冲突、Secret 泄漏、类型丢失、不可复现 |
| 一个文档一个 kernel | 无法做多语言/隔离实验,正是 Jupyter 的局限 |
| 把状态/输出写进 `.mq.md` | Git 噪声;正是要解决的 Jupyter 问题 |
| cell 自动执行 | 违背“未标记即叙述/未调用即数据”;破坏安全默认 |
| v2 做 foreign→Marqdo callback | 重入/死锁/安全复杂;应先稳定数据桥 |
---
## 4. 已锁定的实现边界
### v2 必做
- F0 安全执行内核 + `invoke` 记录 + `exec` 门禁 + 有界 IO + 进程组超时。
- F1 语言注册/发现:15 预设、`probe`、`register`、`unset`、配置、venv。
- F2 JSON 桥:`call` / `run_many` / `output` / `result`。
- F3 持久内核:Python / Node `session_open/eval/close/list`。
- F3.5 状态桥:`session_set/get/names`。
- D1 文档会话服务端:cell index、kernel registry、journal、open/close。
- D2 view notebook:内核选择、Run/Step/Run All/Restart、状态面板、dirty/stale。
- D3 Marqdo statement step 接入 view。
- D4 语法:`内核表` / `会话表` 解析与校验。
- D5 测试、文档、catalog、CHANGELOG。
### v2 不做(明确记录,避免“降级”误解)
- Foreign line-level step(接 DAP 是后续项目)。
- Foreign → Marqdo 函数 callback。
- 跨语言共享对象引用 / 共享内存。
- 全进程快照(只做变量级 JSON 快照)。
- 跨文档全局内核。
- 自动安装依赖。
- 浏览器 wasm 外联。
这些不是“砍掉”,而是**独立阶段**;v2 先把内核/会话/桥做稳。
---
## 5. 风险与对策
| 风险 | 对策 |
|---|---|
| 会话协议脆弱(原生 fd 输出、缓冲) | bootstrap 用原始 stdout;Python `-u`;Node 保存原始 write;超时 kill;文档标注限制 |
| 状态桥隐式化导致不可复现 | 默认显式;`mirror` 后续且默认关 |
| 多内核进程泄漏 | 每文档生命周期;Drop kill;进程组;session_close;测试 |
| 大对象 JSON 拷贝慢 | v2 明确拷贝语义;后续 Arrow/Parquet/文件句柄 |
| `内核表` / `会话表` 名称冲突 | 文档声明为保留绑定名;后续可用 frontmatter 指针重命名 |
| 表格行/单元不一致 | 明确诊断:未声明内核、重复单元、语言不匹配、未入会话 |
| 交互执行顺序混乱 | journal + dirty/stale + Run All canonical + 执行序号 |
| 安全(Secret/环境) | Secret 不进 JSON;env 显式交付;状态面板打码;exec cap |
| 测试环境无 Python | node/bash 主路径;python 条件测试;协议单测 |
---
## 6. 术语表(统一中英文)
| 中文 | English | 含义 |
|---|---|---|
| 外联内核 | foreign kernel | 外部语言进程 |
| 外联会话 | foreign session | 内核实例 + 命名空间 |
| 文档会话 | document session | Marqdo 状态 + 内核注册表 + journal |
| 代码单元 | cell | 绑定名的代码围栏 |
| 内核归属 | kernel assignment | cell → kernel |
| 状态桥 | state bridge | Marqdo 值 ↔ 内核变量 |
| 执行日志 | execution journal | 执行顺序/耗时/结果/hash |
| 新鲜 | clean | 源码未变且已成功执行 |
| 过期 | dirty | 源码变了,结果可能过期 |
| 失效 | stale | 上游依赖变了,需要重跑 |
| 规范执行 | canonical run | 重启后按会话表顺序 Run All |
---
## 7. 决策时间线
1. 用户提出外联库对标 Jupyter、共享状态、单步、切换、双向使用。
2. Agent 阅读 `src/host/foreign.rs`、`src/view`、`src/debug`、`src/host/subtask.rs`、`lib/foreign`、设计文档。
3. Agent 回答:需要 F + D 两层;单步分三种;共享分三层;显式桥。
4. 用户授权 Agent 拍板:安全、最强、不降级、充分测试、文档先行、提交推送后开发。
5. Agent 锁定本文件 §1 的 A–K 结论,进入文档编写与实现。
---
## 8. 后续变更流程
- 任何与本文冲突的实现,先改本文并写明「变更理由 / 影响 / 迁移」。
- 新增核心语法(任何新标记)必须走 `doc/adr/` + `core-surface.md`;本文所有语法均为既有标记的组合。
- 新增会话语言、跨语言数据平面、callback RPC,各自开独立设计文档,不塞进本文件。
+1
View File
@@ -18,6 +18,7 @@
|----|------|------|
| **Intelligence primitive** | `ask` / `stream` / `collect`;结果对象 | `ext/ai/llm` |
| **Agent runtime** | `run` / `step` / `plan` / `route` | `ext/ai/agent` |
| **Sandbox (trial)** | CoW workspace + capped `run` | `ext/ai/sandbox` · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
| **Memory / compile** | episode → skill → policy | `plugins/agent`(ABI;**不进** `src/host`) |
| **Transport** | HTTP / SSE / provider | `ext/ai/llm/openai` · `ollama`;用户不可见 |
+1
View File
@@ -7,6 +7,7 @@
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) · **[agent-framework-2026-09.md](../research/agent-framework-2026-09.md)** |
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) |
| 后续 | 优化波次 O1–O5 见 [ext-ai-optimize.md](ext-ai-optimize.md)(沙盒证明 · Skill Lift · 路由/成本 · lint · 隔离) |
---
+29
View File
@@ -0,0 +1,29 @@
# Roadmap: Agent/LLM 优化波次 O1–O5
| | |
|---|---|
| Status | **Active** |
| Date | 2026-10-16 |
| Design | [ext-ai-optimize.md](../design/ext-ai-optimize.md) |
| Research | [ai-agent-llm-optimize-2026-10.md](../research/ai-agent-llm-optimize-2026-10.md) |
| Prior | [ext-agent-optimize.md](ext-agent-optimize.md) (A0–A4 / Wave B) · [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
## Principles
1. Executable `.mq.md` remains authority; OKF reuses; sandbox proves; LLM explores.
2. No hidden TOOL: loop; no vector-store memory authority; no default shell Agent.
3. Do not edit `doc/next/*`.
## Waves
| Wave | Scope | Gold / deliverable | Status |
|------|-------|--------------------|--------|
| **O1** | A1 opt-in `sandbox=` · A3 profile table · D1 skill · D4 example | `agent-sandbox-optin` · `examples/agent-sandbox-okf` | **done** |
| **O2** | A2 promote proof · B1 OKF meta · B3/E1 harness Skill Lift | `agent-sandbox-promote` · harness subset | **done** |
| **O3** | C1 step route · C2 cost · B6 EFI default | `agent-step-route` · run usage/efi | **done** |
| **O4** | A4/D2 lint · A5 diff review report | `scripts/mq-style-lint.sh` · `sandbox.report` | **done** |
| **O5** | B4 quarantine · C3 offline policy rewrite | `agent-sandbox-quarantine` · `optimize-standing-policy.sh` | **done** |
## Non-goals
F1–F5 · wasmtime CLI embed · default `sandbox=True` without ADR · edit `doc/next/*`
+28
View File
@@ -0,0 +1,28 @@
# Roadmap: `ext/ai/sandbox` (AI CoW trial runtime)
| | |
|---|---|
| Status | **Active** |
| Date | 2026-10-16 |
| Design | [ext-ai-sandbox.md](../design/ext-ai-sandbox.md) |
| Research | [ai-agent-sandbox.md](../research/ai-agent-sandbox.md) |
## Milestones
| ID | Deliverable | Done when |
|----|-------------|-----------|
| S0 | Design + this roadmap + research cross-links | **done** |
| S1 | CoW open/write/read/remove/diff/commit/discard | **done** (`sandbox-cow`) |
| S2 | `run` + default caps + core lib inside run | **done** (`sandbox-run-lib`) |
| S3 | `inspect` + deny plugin.load | **done** (`sandbox-deny`) |
| S4 | Polish: ai-stack + CHANGELOG | **done** |
## Gold samples (target)
- `tests/ext/sandbox-cow.mq.md`
- `tests/ext/sandbox-run-lib.mq.md`
- `tests/ext/sandbox-deny.mq.md`
## Out of scope this wave
wasmtime CLI embed · Wasm ABI plugins · bwrap/microVM · full web in sandbox · auto-wire agent.step · edit `doc/next/*`
+226
View File
@@ -0,0 +1,226 @@
# 外联内核 v2 路线图(F0–F4)
| | |
|---|---|
| 状态 | **F0–F3.5 已落地;F4 进行中** |
| 日期 | 2026-10-17 |
| 层 | Runtime |
| 相关 | [foreign-kernel.md](../design/foreign-kernel.md) · [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [stdlib-foreign.md](../design/stdlib-foreign.md) · [notebook-session.md](notebook-session.md)(D 层路线) |
| 核心表面 Δ | 无 |
> 本路线图只覆盖 **F:外联内核运行时**。共享状态 / 单步 / 切换内核的文档侧在 [notebook-session.md](notebook-session.md)(D 层)。
---
## 0. 现状与目标
v1:`set_cmd` / `run` / `run_lang` / `langs`;临时文件 + 子进程 + stdout 文本;无状态、无结构化结果、无 exec 门禁、无有界 IO、无进程组清理。
v2 目标:安全、可发现、结构化、可持久、可并行,并成为 D 层文档会话的可靠底座。
---
## 1. 阶段总览
| 阶段 | 内容 | 估算 | 可独立发版 |
|---|---|---|---|
| **F0** | 执行内核与安全:Job/Execution、`exec` 门禁、有界 IO、进程组、`invoke` 记录、view 诊断 | 2–3 天 | 是 |
| **F1** | 语言注册与发现:registry、15 预设、probe、register/unset、配置、venv | 2–3 天 | 是 |
| **F2** | JSON 桥与并行:call/call_many、run_many、output/result | 2–3 天 | 是 |
| **F3** | 持久内核:Python/Node session_open/eval/close/list | 3–4 天 | 是 |
| **F3.5** | 状态桥:session_set/get/names | 1–2 天 | 是 |
| **F4** | 打磨、文档、catalog、CHANGELOG、1.5.0 | 1–2 天 | 1.5.0 |
D 层(文档会话)从 F3.5 完成后开始;不要把 D 层塞进 F 层。
---
## 2. F0 — 执行内核与安全
### 内容
- `src/host/foreign.rs` 重构:
- `Job`:lang/source/stdin/input/env/cwd/timeout/args/output/max_output/cmd/keep。
- `Execution`:stdout/stderr/raw bytes/exit/ms/timed_out/truncated/error。
- `ForeignEnv`:cwd/fs_root/specs/caps 快照(供并行)。
- `exec` 门禁:`run` / `invoke` / `run_many` / `probe` / `session_*` 统一检查。
- 有界 IO:读线程保留前 N 字节、继续排空;`truncated`。
- stdin 写线程;EPIPE 忽略。
- 超时:进程组 kill(Unix `process_group(0)` + `kill(-pid)`;Windows `taskkill /T /F`)。
- shell-like argv 切分(引号/转义)。
- `invoke` + 稳定记录。
- `run` / `run_lang` 增加 `env` / `cwd` / `timeout` / `args` / `max_output`。
- view `/api/foreign-run` 返回完整记录;JS 显示 stderr / exit / ms。
- `set_cmd` L1 补 `args`。
### 验收
- 既有 `lib_foreign_*` / `lib_subtask_foreign` 绿(python 可用时)。
- 新增 node/bash 金样例:非 0 退出、stderr、超时、env/cwd、截断。
- `exec=false` 拒绝。
- `cargo test` 绿;release build;wasm check。
### 主要文件
`src/host/foreign.rs` · `src/host/mod.rs` · `src/host/subtask.rs` · `src/view/mod.rs` · `src/view/html.rs` · `src/view/debug_page.rs` · `Cargo.toml` · `tests/gold.rs` · `tests/lib/foreign-*.mq.md`。
---
## 3. F1 — 语言注册与发现
### 内容
- `src/foreign/registry.rs`(纯逻辑):
- 15 预设、别名、扩展名、版本参数、会话能力。
- 模板占位符 `{file}` / `{dir}` / `{base}` / `{inline}` / `{lang}` / `{cwd}`。
- venv 探测、PATH 查找、shell-like 切分、配置解析。
- `HostContext`:
- `foreign_specs`、`foreign_config_loaded`。
- `probe` 缓存(可选)。
- API:`probe` / `langs` / `register` / `unset` / `load_config`。
- 配置:`.marqdo/foreign.toml` + `MARQDO_FOREIGN_CONFIG`;优先级见设计。
- `MARQDO_FOREIGN_<LANG>` 支持 JSON 数组与引号。
- `subtask` 继承注册/配置。
### 验收
- `probe` 对 node / bash 给出 path + version;缺失语言 `ok=false` 不 panic。
- 配置可把 `python` 指向 venv;模板可跑 `go run`(若本机有 go)。
- `langs` 含预设;`unset` 回退预设。
- 单元测试:切分、模板、别名、扩展名。
---
## 4. F2 — JSON 桥与并行
### 内容
- `call` / `call_many`;`invoke` 的 `input` / `output` / `result` / `result_error`。
- `Value ↔ JSON` 复用 `host::json`;`bytes` base64。
- `run_many` 并行引擎:`ForeignEnv` 快照、线程上限 32、结果同序、单项 panic 隔离。
- `call_many` 全跑完再报错(清理所有子进程)。
- 文档:Python / Node JSON 样板。
### 验收
- `call` 单列表 → map,mean 为 Num;嵌套 list/map 往返。
- `run_many` 顺序稳定;单项失败不影响其它项。
- 大输入(>8 KiB)走 `MARQDO_INPUT_FILE`。
- 并发上限与超时生效。
---
## 5. F3 — 持久内核
### 内容
- `src/host/foreign_session.rs`:
- Python / Node bootstrap(嵌入式常量)。
- 启动、reader/writer、严格串行、超时、崩溃、drop 清理。
- `session_open` / `session_eval` / `session_close` / `session_list`。
- 会话记录:与 invoke 同形 + `id` / `alive`。
- 会话环境:cwd / env / cmd;`MARQDO_*`。
- `HostContext` 字段(cfg exec-host)+ Drop。
### 验收
- Node:`let x=41` → `x+1` → 42;`console.log` 捕获;异常不杀会话。
- Python:同(有 python 时)。
- 超时 → kill + `alive=false`;close/drop 无遗留进程。
- 会话与 `subtask` 边界:不继承。
---
## 6. F3.5 — 状态桥
### 内容
- `session_set` / `session_get` / `session_names`。
- 值:Marqdo → JSON → kernel;kernel → JSON → Marqdo。
- 名称校验;Secret 规则;错误可读。
- 与 `session_eval` 同一线路,严格串行。
- L1 文档 + 金样例。
### 验收
- Node:`session_set xs=[1,2,3]`,`session_eval sum(xs)` → 6;`session_get` 取回。
- 复杂嵌套 map/list 往返。
- 不存在变量 → None + 可读诊断。
- 非 JSON 可序列化 → 错误说明。
---
## 7. F4 — 打磨与发布
- `history`(可选)/ `cache`(可选,默认关)。
- view 命令记忆 / Ctrl+Enter / 错误分块。
- `lib/foreign.mq.md` / `lib/外联.mq.md` 全量。
- `public/stdlib/*` 示例。
- catalog 重新生成;CHANGELOG;版本 1.5.0。
- 性能:空跑、100 次调用、会话 vs 一次性。
### 验收
- 新函数全部有中文/英文文档与示例。
- `marqdo catalog`、`public/` 构建通过。
- 手工 view Run 一个 node 卡片,显示 stdout/stderr/exit/ms。
---
## 8. 测试矩阵
> 当前环境:node / bash / sh / perl 可用,python3 不可用。新金样例以 node + bash 为主;python 用 `python_available()` 条件跳过。
| 测试 | 依赖 | 断言 |
|---|---|---|
| 既有 3 个 foreign 用例 | python | 兼容 |
| `foreign-invoke` | node | 记录字段 |
| `foreign-env-cwd` | node | env/cwd/MARQDO_* |
| `foreign-timeout` | node | timed_out |
| `foreign-call-json` | node | 类型往返 |
| `foreign-call-many` / `run-many` | node | 顺序/隔离 |
| `foreign-session` | node | 跨 eval |
| `foreign-session-set-get` | node | 状态桥 |
| `foreign-session-timeout` | node | alive=false |
| `foreign-probe` | node | path/version |
| `foreign-register` | node | 模板 |
| `foreign-config` | node | 配置 |
| `foreign-stdout-stderr` | bash | 成功也有 stderr |
| `foreign-caps` | 无 | 拒绝 |
| 单元测试 | 无 | 切分/模板/别名/JSON |
Windows:`python_available` / `bash_available` 守卫;进程组 `taskkill` 分支编译通过。
---
## 9. 兼容性
- `run` / `run_lang` / `set_cmd` / `langs` 兼容;只增可选参数。
- `run` 成功仍返回 stdout;非 0 仍报错。
- 大输出从“报错”改为“截断 + truncated”(更安全;CHANGELOG 写明)。
- `langs` 扩展为预设 ∪ 注册 ∪ 配置。
- HostFn id 末尾追加(196+)。
- 无核心表面 Δ。
---
## 10. 风险
| 风险 | 缓解 |
|---|---|
| 会话协议脆弱 | 原始 stdout;`-u`;超时 kill;测试;文档限制 |
| 并行进程过多 | 默认 4 / 上限 32;超时;输出上限 |
| 配置优先级难记 | 设计文档固定表;`probe` 显示实际 path |
| 模板 shell 注入 | 默认不 shell;路径引擎生成;文档警示 |
| 大输出截断改变 v1 行为 | CHANGELOG;`truncated` 可检测 |
| wasm 编译 | 新字段 cfg 隔离;registry 纯逻辑 |
---
## 11. 完成定义
- F0–F3.5 全部验收。
- `cargo test` 绿;release build;wasm check。
- 文档/CHANGELOG/catalog 更新。
- 提交并推送。
- 进入 D 层([notebook-session.md](notebook-session.md))。
+177
View File
@@ -0,0 +1,177 @@
# 文档会话路线图(D0–D5)
| | |
|---|---|
| 状态 | **D1–D3 已落地(首版);D4–D5 待做** |
| 日期 | 2026-10-17 |
| 层 | Runtime + Document(view 服务端 / 前端) |
| 相关 | [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-kernel.md](../design/foreign-kernel.md) · [foreign-v2.md](foreign-v2.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) |
| 核心表面 Δ | 无 |
> F 层让“外部语言能持久运行”;D 层让“文档里的多个 cell 像 notebook 一样共享状态、单步、切换内核”。两层分开验收。
---
## 0. 依赖
- **F3**:Python / Node 持久内核。
- **F3.5**:`session_set/get/names`。
- 现有 `DebugController`(Marqdo 语句单步)。
- 现有 `writeback` / `annot` / view 结构。
没有 F3/F3.5,D2 只能做一次性 Run,不是共享状态。
---
## 1. 阶段总览
| 阶段 | 内容 | 估算 |
|---|---|---|
| **D0** | 设计/语法/决策文档 | 已完成 |
| **D1** | `src/notebook/`:cell index、表解析、session 结构、诊断 | 2–3 天 |
| **D2** | 服务端 API:open/close/cell run/step/run_all/restart/interrupt | 3–4 天 |
| **D3** | view UI:工具栏、cell 徽标、kernel 下拉、状态面板、journal | 3–4 天 |
| **D4** | statement step、dirty/stale、writeback | 2–3 天 |
| **D5** | replay、持久化、并发优化、测试补全、发布 | 2–3 天 |
---
## 2. D1 — Cell index 与表解析
### 内容
- 新模块 `src/notebook/`:
- `cell.rs`:从 AST 提取绑定名代码围栏;id/name/lang/line/source hash。
- `syntax.rs`:读取 `内核表` / `会话表`;中英列名。
- `session.rs`:`DocumentSession` 结构、kernel registry、value store、journal。
- `diag.rs`:重复/未知/语言不匹配/未入会话诊断。
- 自动模式:无表 → 文档顺序 + 默认内核。
- 解析器不改;只遍历 `Module.functions` + `Stmt::Assign { value: Expr::Code }`。
- 测试:单元 + `tests/notebook/*.mq.md`。
### 验收
- 两个 Python cell + 一个会话表 → cells 顺序、kernel 归属正确。
- 无表 → 自动顺序。
- 未知内核/未知单元/重复/语言不匹配 → 可读诊断。
- 未绑定围栏不进入 cell index。
---
## 3. D2 — 服务端 API
### 内容
- `src/view/notebook_api.rs`(或 `view/session_api.rs`):
- open / close / reload
- cell run / step / run_all
- kernel restart / interrupt / assign
- state list / push / pull
- journal
- Session 存储:`OnceLock<Mutex<HashMap<String, Arc<DocumentSession>>>>`(类似 debug sessions)。
- 每个文档一个 session;key = 相对路径。
- 执行线程:cell 执行不阻塞 HTTP;响应返回记录;SSE/EventBus 可选。
- 错误统一 JSON。
### 验收
- open 返回 cells/kernels/journal。
- cell run:never→running→clean/error;状态更新。
- step:按会话顺序执行下一个。
- run_all:按顺序;restart 选项。
- 同 kernel 串行;不同 kernel 可并行。
- close/drop kill 所有 kernel。
- API 单测/集成测试。
---
## 4. D3 — View UI
### 内容
- 工具栏:Run All / Restart & Run All / Step Cell / Step Statement / Kernel 状态 / Restart / Interrupt / State / Journal。
- Code card:
- 状态徽标(never/clean/dirty/stale/error/running/unlisted)
- kernel 下拉
- Run / Step
- 输出区(stdout/stderr/result/truncated)
- 执行序号 / 耗时
- 状态面板:
- Marqdo 值 / kernel 变量分栏
- Push / Pull / Refresh
- Secret 打码、大对象摘要
- Journal 面板:表格 + 跳转 + 导出。
- 键盘:Ctrl/Cmd+Enter、Shift+Enter、F5、F10。
- 静态导出的 Run 仍隐藏。
### 验收
- 手工冒烟:两个 Python cell 共享 `x`;切换 kernel 后隔离;Restart 清状态。
- 状态面板 Push/Pull。
- 错误 cell 红色徽标 + stderr。
- 页面刷新后 session 仍在(服务端内存)。
---
## 5. D4 — Statement step / dirty / writeback
### 内容
- Statement step:复用 `DebugController`,与 DocumentSession 关联;暂停点显示变量。
- dirty:reload 后 source hash 变化。
- stale:按会话顺序,上游变更 → 下游 stale(v2 近似)。
- writeback:单 cell / 全部;`<!-- marqdo-out -->`;不自动。
- 运行历史 / 执行序号。
### 验收
- Statement step 在 view 中可用;外联调用原子完成。
- 编辑 cell → dirty;Run All 后 clean。
- 上游变更 → 下游 stale。
- 显式 writeback 写入文档;不自动改文件。
---
## 6. D5 — Replay / 持久化 / 发布
### 内容
- Journal replay:新 kernel,按 journal 顺序/输入 hash 重放;比较 stdout/result hash;divergence 报告。
- 可选持久化 `.marqdo/sessions/<doc-hash>.json`(kernel/cell 归属/journal/value store 摘要;默认 git 忽略)。
- 并发优化:不同 kernel 并行;同 kernel 串行。
- 测试补全;文档;catalog;CHANGELOG。
- 版本:D 层随 1.5.x。
### 验收
- Replay 能复现 clean 会话;dirty 输入给出 divergence。
- 关闭/重启服务无进程泄漏。
- 文档完整;金样例绿。
---
## 7. 测试矩阵
| 测试 | 断言 |
|---|---|
| `notebook/kernels.mq.md` | 内核表/会话表解析 |
| `notebook/auto-session.mq.md` | 无表自动顺序 |
| `notebook/shared-state.mq.md` | 同 kernel 共享变量 |
| `notebook/isolated-kernels.mq.md` | 不同 kernel 隔离 |
| `notebook/step.mq.md` | cell step 顺序 |
| `notebook/state-bridge.mq.md` | Marqdo ↔ kernel 推拉 |
| `notebook/dirty.mq.md` | 编辑 → dirty/stale |
| `notebook/invalid-*.mq.md` | 诊断 |
| API 集成 | open/run/step/run_all/restart/interrupt/close |
| 安全 | exec=false、cwd 越界、超时、Secret 打码 |
依赖 node 为主;python 条件跳过。
---
## 8. 完成定义
- D1–D4 验收;D5 可选(replay/持久化)。
- 文档会话与 F 层联调通过。
- 手工 view 冒烟:共享状态 / 单步 / 切换 / 状态面板 / journal。
- 测试绿;文档更新;提交推送。
+13
View File
@@ -0,0 +1,13 @@
# agent-sandbox-okf(O1)
演示 **opt-in 沙盒试跑 + 表风格**(少 json 胶水):`agent.trial` 写入先落 upper,`commit=False` 时宿主不变,成功后再 `commit=True`。
```bash
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/ext"
./target/release/marqdo run examples/agent-sandbox-okf/index.mq.md
```
期望:`dry-ok` · `host-clean` · `wet-ok` · `proof-visible` · `profile-default`。
见 [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md) · 金样 [agent-sandbox-optin.mq.md](../../tests/ext/agent-sandbox-optin.mq.md)。
+59
View File
@@ -0,0 +1,59 @@
---
title: agent-sandbox-okf — trial then commit
description: >
O1 example: opt-in sandbox trial with GFM-table returns and link-index reads.
import agent:ext/ai/agent.mq.md
import fs:lib/fs.mq.md
---
# main
Short demo: write via `agent.trial`, prove the host is clean until commit.
**had = fs.exists path="_example_sbx"**
1. `had`
> fs.remove path="_example_sbx"
2. *
**_ = 0**
> fs.make_dir path="_example_sbx"
**dry = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=False**
**dry_ok = [ok](dry)**
**dry_committed = [committed](dry)**
1. `dry_ok`
1. not `dry_committed`
> print text=dry-ok
2. *
> print text=dry-bad-commit
2. *
> print text=dry-fail
**leaked = fs.exists path="_example_sbx/note.txt"**
1. `leaked`
> print text=host-leaked
2. *
> print text=host-clean
**wet = agent.trial root="_example_sbx" write_path="note.txt" text=sandbox-okf commit=True**
**wet_ok = [ok](wet)**
**wet_committed = [committed](wet)**
1. `wet_ok`
1. `wet_committed`
> print text=wet-ok
2. *
> print text=wet-no-commit
2. *
> print text=wet-fail
**body = fs.read_text path="_example_sbx/note.txt"**
1. `body` == "sandbox-okf"
> print text=proof-visible
2. *
> print text=proof-missing
**pname = [name]([profile](wet))**
1. `pname` == "default"
> print text=profile-default
2. *
> print text=profile-other
+1 -1
View File
@@ -1 +1 @@
1.3.1
1.5.0
+641 -336
View File
File diff suppressed because it is too large. Load diff
+42 -15
View File
@@ -5,6 +5,7 @@ description: >-
OpenAI-compatible and Ollama HTTP stay behind the semantic surface.
import sys:lib/sys.mq.md
import json:lib/json.mq.md
import table:lib/table.mq.md
import fs:lib/fs.mq.md
import text:lib/text.mq.md
import openai:ext/ai/llm/openai.mq.md
@@ -25,14 +26,14 @@ Collapse a stream event list to final answer text (`done.result` or `error.messa
**answer = ""**
- [ev](events)
**t = [type](ev)**
**t = > json.get value=`ev` key="type"**
1. `t` == "done"
**answer = [result](ev)**
**answer = > json.get value=`ev` key="result"**
2. `t` == "error"
**answer = [message](ev)**
**answer = > json.get value=`ev` key="message"**
3. `t` == "delta"
4. `t` == "text"
**chunk = [text](ev)**
**chunk = > json.get value=`ev` key="text"**
1. `chunk`
**answer = answer + chunk**
2. *
@@ -167,7 +168,8 @@ Module convenience: create a default handle and return **answer text**. Pass `pa
**m = > create model=`model` base_url=`base_url` api_key=`api_key`**
**r = > m.ask prompt=`p`**
*[text](r)*
**_ret = > json.get value=`r` key="text"**
*_ret*
# llm
+ `model`=None
@@ -283,9 +285,21 @@ Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `
**text = > json.get value=`pack` key="text"**
**usage = > json.get value=`pack` key="usage"**
**finish = > json.get value=`pack` key="finish"**
**err = > json.get value=`pack` key="error"**
**tc = > json.get value=`pack` key="tool_calls"**
1. not `tc`
**tc = > json.parse text=[]**
**tc = > table.empty_list**
2. *
**_ = 1**
1. not `text`
**text = ""**
2. *
**_ = 1**
1. not `finish`
1. `err`
**finish = "error"**
2. *
**finish = "stop"**
2. *
**_ = 1**
@@ -293,16 +307,27 @@ Hoist receiver fields before the result table — table cells can shadow `self`
column names (`model`, `usage`), so `[model](self)` / `[total_tokens](usage)`
inside the table is unsafe.
**mdl = [model](self)**
**b = [backend](self)**
**nm = [name](self)**
**tt = [total_tokens](usage)**
**mdl = > json.get value=`self` key="model"**
**b = > json.get value=`self` key="backend"**
**nm = > json.get value=`self` key="name"**
1. `usage`
**tt = > json.get value=`usage` key="total_tokens"**
2. *
**tt = 0**
1. not `tt`
**tt = 0**
2. *
**_ = 1**
1. `err`
**calls = 0**
2. *
**calls = 1**
`result` =
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls |
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls | error |
|------|-------|--------|---------|-------|------|-----------|--------|------------|-------|
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | `calls` | `tt` | `tc` | `err` |
*result*
@@ -345,10 +370,12 @@ Internal / compatibility primitive. Prefer `ask` / `stream` in new code.
1. `stream`
**pack = > self.complete_result prompt=`prompt` stream=True echo=`echo`**
*[events](pack)*
**_ret = > json.get value=`pack` key="events"**
*_ret*
2. *
**pack = > self.complete_result prompt=`prompt` stream=False echo=`echo`**
*[text](pack)*
**_ret = > json.get value=`pack` key="text"**
*_ret*
## chat
+ `prompt`
+65 -26
View File
@@ -4,6 +4,7 @@ description: >-
OpenAI-compatible chat completions transport (HTTP + SSE).
Prefers optional plugins/llm ABI when present; falls back to lib/net.
Used by ext/ai/llm; authors should prefer llm.ask / llm.stream.
Result packs are GFM tables / table.put (code-as-documentation).
import net:lib/net.mq.md
import json:lib/json.mq.md
import table:lib/table.mq.md
@@ -53,21 +54,18 @@ Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list).
**choices = > json.get value=`data` key="choices"**
1. not `choices`
**empty = > json.parse text=[]**
*empty*
*> table.empty_list*
2. *
**c0 = [1](choices)**
**msg = > json.get value=`c0` key="message"**
1. not `msg`
**empty = > json.parse text=[]**
*empty*
*> table.empty_list*
2. *
**tc = > json.get value=`msg` key="tool_calls"**
1. `tc`
*tc*
2. *
**empty = > json.parse text=[]**
*empty*
*> table.empty_list*
## chat_completions
+ `base_url`
@@ -79,7 +77,7 @@ Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list).
+ `suffix`=/chat/completions
+ `bearer`="Bearer "
POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`.
POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. Soft transport / HTTP failures return `finish=error` packs (never abort the VM).
**p = > plugin.native_path name="llm"**
1. `p`
@@ -106,40 +104,81 @@ POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_c
**req = > table.put in=`req` at="stream" value=True**
**body = > json.stringify value=`req`**
**resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo`**
1. [status](resp) == 200
**pack = > json.parse text={"finish":"stop"}**
**pack = > json.set map=`pack` key="events" value=[events](resp)**
**st = > json.get value=`resp` key="status"**
1. `st` == 200
**evs = > json.get value=`resp` key="events"**
`pack` =
| finish | events |
|--------|--------|
| stop | `evs` |
*pack*
2. *
> print text=ext/ai/llm/openai: HTTP error (stream)
> print text=[status](resp)
> sys.exit code=1
Soft transport / HTTP failure — structured pack, never abort the VM.
**msg = "HTTP " + `st`**
**evs = > json.get value=`resp` key="events"**
1. `evs`
**e0 = > at value=`evs` index=0**
**m2 = > json.get value=`e0` key="message"**
1. `m2`
**msg = `m2`**
`pack` =
| finish | text | error | events |
|--------|------|-------|--------|
| error | "" | `msg` | `evs` |
*pack*
2. *
**body = > json.stringify value=`req`**
**resp = > net.http_post url=`url` body=`body` headers=`headers`**
1. [status](resp) == 200
**data = > json.parse text=[body](resp)**
**msg = [message]([1]([choices](data)))**
**st = > json.get value=`resp` key="status"**
1. `st` == 200
**raw = > json.get value=`resp` key="body"**
**data = > json.parse text=`raw`**
**choices = > json.get value=`data` key="choices"**
**choice0 = > at value=`choices` index=0**
**msg = > json.get value=`choice0` key="message"**
**text = > json.get value=`msg` key="content"**
1. not `text`
**text = ""**
2. *
**_ = 1**
**usage = > usage_from data=`data`**
**fr = > json.get value=[1]([choices](data)) key="finish_reason"**
**fr = > json.get value=`choice0` key="finish_reason"**
1. not `fr`
**fr = "stop"**
2. *
**_ = 1**
**tc = > tool_calls_from data=`data`**
**pack = > json.parse text={"finish":"stop"}**
**pack = > json.set map=`pack` key="text" value=`text`**
**pack = > json.set map=`pack` key="usage" value=`usage`**
**pack = > json.set map=`pack` key="finish" value=`fr`**
**pack = > json.set map=`pack` key="tool_calls" value=`tc`**
`pack` =
| finish | text | usage | tool_calls |
|--------|------|-------|------------|
| `fr` | `text` | `usage` | `tc` |
*pack*
2. *
> print text=ext/ai/llm/openai: HTTP error
> print text=[status](resp)
> print text=[body](resp)
> sys.exit code=1
Soft transport / HTTP failure — structured pack, never abort the VM.
**raw = > json.get value=`resp` key="body"**
**msg = "HTTP " + `st`**
1. `raw`
**msg = `msg` + ": " + `raw`**
`usage0` =
| prompt_tokens | completion_tokens | total_tokens |
|---------------|-------------------|--------------|
| 0 | 0 | 0 |
**empty_tc = > table.empty_list**
`pack` =
| finish | text | error | usage | tool_calls |
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
+25
View File
@@ -0,0 +1,25 @@
---
title: step-route policy (O3)
description: >
Table-driven map from step class → Adaptive Routing backend.
Readable authority for agent.step_route; do not invent a second dialect.
---
# Step class → backend
Authors and `agent.step_route` read this table. Backends match Adaptive Routing:
`marqdo` | `small-llm` | `llm` | `auto`.
**routes = **
| kind | backend | note |
|------|---------|------|
| lookup | marqdo | OKF / kb skill hit — no parent LLM |
| patch | small-llm | Local patch / soft match |
| sandbox_run | marqdo | CoW trial of `.mq.md` |
| net | llm | Needs network / toolful turn |
| default | auto | Cascade policy → kb → small-llm |
# main
*routes*
+191
View File
@@ -0,0 +1,191 @@
---
title: ext/ai/sandbox
description: >-
CoW trial workspace for AI-generated Marqdo: open / run / diff / commit.
Native work lives in plugins/agent (`sandbox_*` → host_query).
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import table:lib/table.mq.md
import fs:lib/fs.mq.md
---
Load the agent plugin once per call (same pattern as other `ext/ai` helpers).
Capability profiles are GFM tables under `## profile` (readable authority; `open` / `inspect` echo them). Do not invent a second table dialect.
## ensure_plugin
**p = plugin.native_path name="agent"**
1. `p`
> plugin.load path=`p`
2. *
> print text=ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)
> sys.exit code=1
## profile
+ `name`=default
Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`.
Catalog (documentation + authority):
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| default | true | false | false | false |
| readonly | false | false | false | false |
1. `name` == "readonly"
**row = **
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| readonly | false | false | false | false |
2. *
**row = **
| name | fs_write | exec | net | plugin |
|------|----------|------|-----|--------|
| default | true | false | false | false |
*row*
## open_native
+ `root`=None
Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade.
> ensure_plugin
1. `root`
*> sandbox_open root=`root`*
2. *
*> sandbox_open*
## open
+ `root`=None
+ `profile`=default
Open a CoW session. Optional `root=` (directory). Default: entry file directory.
`profile=` selects the caps row from `## profile` (echoed by `inspect`).
**sess = open_native root=`root`**
**prof = profile name=`profile`**
**sess = table.put in=`sess` at="profile" value=`prof`**
*sess*
## write
+ `id`
+ `path`
+ `text`
Write text into the session upper layer (host tree unchanged until `commit`).
> ensure_plugin
*> sandbox_write id=`id` path=`path` text=`text`*
## read
+ `id`
+ `path`
Read through CoW (upper, else lower; whiteout misses).
> ensure_plugin
*> sandbox_read id=`id` path=`path`*
## remove
+ `id`
+ `path`
Logical delete (whiteout).
> ensure_plugin
*> sandbox_remove id=`id` path=`path`*
## diff
+ `id`
List of `{ path, kind }` pending changes (`write` | `remove`).
> ensure_plugin
*> sandbox_diff id=`id`*
## commit
+ `id`
Apply upper / whiteout to the real workspace root.
> ensure_plugin
*> sandbox_commit id=`id`*
## discard
+ `id`
Drop the session without writing the host tree.
> ensure_plugin
*> sandbox_discard id=`id`*
## run
+ `id`
+ `source`=None
+ `path`=None
Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW).
Pass `source=` or `path=` (relative to session root).
> ensure_plugin
1. `source`
*> sandbox_run id=`id` source=`source`*
2. `path`
*> sandbox_run id=`id` path=`path`*
3. *
> print text=ext/ai/sandbox.run: need source= or path=
> sys.exit code=1
## inspect_native
+ `id`
> ensure_plugin
*> sandbox_inspect id=`id`*
## inspect
+ `id`
+ `profile`=default
Native caps / change counts, plus the GFM `## profile` row under key `profile`.
**raw = inspect_native id=`id`**
**prof = profile name=`profile`**
**out = table.put in=`raw` at="profile" value=`prof`**
*out*
## report
+ `id`
+ `path`=sandbox-diff.md
O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite).
**pending = diff id=`id`**
**n = len value=`pending`**
**body = "# Sandbox diff report\n\nPending changes: "**
**body = body + n**
**body = body + "\n\n| path | kind |\n|------|------|\n"**
- [row](pending)
**p = [path](row)**
**k = [kind](row)**
**body = body + "| "**
**body = body + p**
**body = body + " | "**
**body = body + k**
**body = body + " |\n"**
> fs.write_text path=`path` text=`body`
**out = **
| path | count |
|------|-------|
| `path` | `n` |
*out*
+57 -21
View File
@@ -3,6 +3,8 @@ title: ext/ai/智能体
description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编译经 ABI v2 agent 插件(情景 → 学习 → llm_free)。
导入 大模型:ext/ai/大模型.mq.md
import agent:ext/ai/agent.mq.md
import sandbox:ext/ai/sandbox.mq.md
import table:lib/table.mq.md
import json:lib/json.mq.md
导入 系统:lib/系统.mq.md
导入 自写回:lib/自写回.mq.md
@@ -86,13 +88,14 @@ import json:lib/json.mq.md
> 系统.退出 码=1
**id = > agent_alloc**
**h = > json.parse text={"_type":"智能体"}**
**h = > json.set map=`h` key="id" value=`id`**
**h = > json.set map=`h` key="model" value=`大模型`**
**h = > json.set map=`h` key="tools" value=`工具`**
`h` =
| _type | id | model | tools |
|-------|-----|-------|-------|
| 智能体 | `id` | `大模型` | `工具` |
1. `站立提示`
**h = > json.set map=`h` key="standing" value=`站立提示`**
**h = table.put in=`h` at="standing" value=`站立提示`**
2. *
**_ = 1**
@@ -106,23 +109,42 @@ import json:lib/json.mq.md
> agent_history_clear id=`id`
****
## 试跑
+ `路径`=None
+ `源码`=None
+ `根目录`=None
+ `写入路径`=None
+ `文本`=None
+ `提交`=真
+ `配置`=default
O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。
*> agent.trial path=`路径` source=`源码` root=`根目录` write_path=`写入路径` text=`文本` commit=`提交` profile=`配置`*
## 单步
+ `任务`
+ `写回`=真
+ `流式`=假
+ `打印增量`=假
+ `沙盒`=假
+ `沙盒配置`=default
原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。
**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`**
**id = > json.get value=`自` key="id"**
**model = > json.get value=`自` key="model"**
**tools = > json.get value=`自` key="tools"**
**user_turn = > json.parse text={"role":"user"}**
**user_turn = > json.set map=`user_turn` key="content" value=`任务`**
`user_turn` =
| role | content |
|------|---------|
| user | `任务` |
> agent_history_append id=`id` item=`user_turn`
1. `流式`
@@ -134,9 +156,11 @@ import json:lib/json.mq.md
**reply = > trim value=`reply`**
**decision = reply**
**tool_name = > 提取工具名 回复=`reply`**
**out = > json.parse text={"status":"ok"}**
**out = > json.set map=`out` key="task" value=`任务`**
**out = > json.set map=`out` key="decision" value=`decision`**
`out` =
| status | task | decision |
|--------|------|----------|
| ok | `任务` | `decision` |
1. `tool_name`
**tool_out = > 运行工具 工具=`tools` 名=`tool_name`**
@@ -144,8 +168,8 @@ import json:lib/json.mq.md
**deny = > split value=`tool_s` sep="Tool not allowed"**
**deny_n = > len value=`deny`**
1. `deny_n` > 1
**out = > json.set map=`out` key="status" value="error"**
**out = > json.set map=`out` key="error" value=`tool_s`**
**out = table.put in=`out` at="status" value="error"**
**out = table.put in=`out` at="error" value=`tool_s`**
**reply = tool_s**
2. *
**task_s = > json.stringify value=`任务`**
@@ -161,16 +185,25 @@ import json:lib/json.mq.md
**reply = > 大模型.流式结果 事件=`evs2`**
2. *
**reply = > model.运行 提示=`fp`**
**out = > json.set map=`out` key="tool" value=`tool_name`**
**out = > json.set map=`out` key="tool_result" value=`tool_s`**
**out = > json.set map=`out` key="result" value=`reply`**
**out = table.put in=`out` at="tool" value=`tool_name`**
**out = table.put in=`out` at="tool_result" value=`tool_s`**
**out = table.put in=`out` at="result" value=`reply`**
2. *
**out = > json.set map=`out` key="result" value=`reply`**
**out = table.put in=`out` at="result" value=`reply`**
**as_turn = > json.parse text={"role":"assistant"}**
**as_turn = > json.set map=`as_turn` key="content" value=`reply`**
`as_turn` =
| role | content |
|------|---------|
| assistant | `reply` |
> agent_history_append id=`id` item=`as_turn`
1. `沙盒`
**配置行 = sandbox.profile name=`沙盒配置`**
**out = table.put in=`out` at="sandbox_profile" value=`配置行`**
2. *
**_ = 1**
1. `写回`
**body = > json.stringify value=`out`**
**st = > json.get value=`out` key="status"**
@@ -296,14 +329,17 @@ Engineering First Information 门闩。转发 `agent.preflight`。
+ `强制`=False
+ `路由`=auto
+ `路由模型`=None
+ `沙盒`=False
+ `沙盒配置`=default
+ `工程预检`=True
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。
v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`|`marqdo`|`small-llm`|`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。
**model = > json.get value=`self` key="model"**
**tools = > json.get value=`self` key="tools"**
**standing = > json.get value=`self` key="standing"**
**en = > agent.agent model=`model` tools=`tools` standing=`standing`**
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型`*
*> en.run task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` learn=`学习` verify=`校验` writeback=`写回` reuse=`复用` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` improve_every=`改进周期` explore_n=`探索次数` max_rounds=`最大轮次` stream=`流式` echo=`打印增量` trace=`轨迹` force=`强制` router=`路由` router_model=`路由模型` sandbox=`沙盒` sandbox_profile=`沙盒配置` efi=`工程预检`*
## 路由
+ `任务`
+63
View File
@@ -0,0 +1,63 @@
---
title: ext/ai/沙盒
description: >-
AI 试跑 CoW 工作区:打开 / 运行 / 差异 / 提交(中文面,委托英文 sandbox 模块)。
import sandbox:ext/ai/sandbox.mq.md
---
## 打开
+ `根`=None
*> sandbox.open root=`根`*
## 写入
+ `id`
+ `路径`
+ `文本`
*> sandbox.write id=`id` path=`路径` text=`文本`*
## 读取
+ `id`
+ `路径`
*> sandbox.read id=`id` path=`路径`*
## 删除
+ `id`
+ `路径`
*> sandbox.remove id=`id` path=`路径`*
## 差异
+ `id`
*> sandbox.diff id=`id`*
## 提交
+ `id`
*> sandbox.commit id=`id`*
## 丢弃
+ `id`
*> sandbox.discard id=`id`*
## 运行
+ `id`
+ `源码`=None
+ `路径`=None
1. `源码`
*> sandbox.run id=`id` source=`源码`*
2. `路径`
*> sandbox.run id=`id` path=`路径`*
3. *
> print text=沙盒.运行: 需要 源码= 或 路径=
> sys.exit code=1
## 检查
+ `id`
*> sandbox.inspect id=`id`*
+3 -2
View File
@@ -1,9 +1,10 @@
---
title: ext/net/url
description: URL helpers (stdlib host wrappers). ADR 0007.
description: URL helpers (stdlib wrappers). ADR 0007.
import net:lib/net.mq.md
---
## encode
+ `text`
*> host_url_encode text=`text`*
*> net.url_encode text=`text`*
+183 -6
View File
@@ -8,29 +8,206 @@ Run bound code fences and inline sources via local interpreters.
## set_cmd
+ `lang`
+ `cmd`
+ `args`=None
Bind interpreter command cmd for language lang.
Bind interpreter command cmd for language lang; optional extra argv.
*> host_foreign_set_cmd lang=`lang` cmd=`cmd`*
*> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`*
## run
+ `code`
+ `stdin`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
+ `args`=None
+ `max_output`=None
Run a bound code fence value; optional stdin.
Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds),
extra argv and output cap. Returns stdout text; non-zero exit is an error.
Caller: [foreign.run] code=`block`
*> host_foreign_run code=`code` stdin=`stdin`*
*> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`*
## run_lang
+ `lang`
+ `source`
+ `stdin`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
+ `args`=None
+ `max_output`=None
Run source text with language lang; optional stdin.
Run source text with language lang; same options as run.
*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin`*
*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`*
## invoke
+ `code`=None
+ `lang`=None
+ `source`=None
+ `stdin`=None
+ `input`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
+ `args`=None
+ `output`=auto
+ `max_output`=None
+ `cmd`=None
+ `keep`=False
Run code or lang+source and return a record map instead of raising on process
failure. Fields: ok, code, stdout, stderr, ms, lang, cmd, timed_out, truncated,
result, result_error, error, script, cached.
`input` is encoded as JSON on stdin (mutually exclusive with `stdin`). `output`
is auto | text | json | lines. `cmd` overrides the interpreter for this call.
*> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`*
## probe
+ `lang`=None
Probe one language, or every known language when lang is omitted. Returns
{lang, cmd, path, ok, version, error} (a list when lang is omitted).
*> host_foreign_probe lang=`lang`*
## register
+ `lang`
+ `cmd`=None
+ `args`=None
+ `template`=None
+ `ext`=None
+ `env`=None
+ `version_args`=None
Register a language invocation. Provide cmd (+args) or template (placeholders
{file}, {dir}, {base}, {inline}, {lang}, {cwd}); they are mutually exclusive.
*> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`*
## unset
+ `lang`
Remove a process-local registration. Presets/config/env still apply.
*> host_foreign_unset lang=`lang`*
## load_config
+ `path`=None
Load .marqdo/foreign.toml (or an explicit path); returns the number of language
tables read.
*> host_foreign_load_config path=`path`*
## call
+ `code`=None
+ `lang`=None
+ `source`=None
+ `input`=None
+ `stdin`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
+ `args`=None
JSON-in / JSON-out call: encode `input` on stdin, parse stdout JSON and return
the value (empty stdout -> None). Raises on process failure or invalid JSON.
*> host_foreign_call code=`code` lang=`lang` source=`source` input=`input` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args`*
## run_many
+ `runs`
+ `concurrency`=4
Run a list of code values or invoke-option maps in parallel; returns records in
input order. One failing item does not stop the others.
*> host_foreign_run_many runs=`runs` concurrency=`concurrency`*
## call_many
+ `inputs`
+ `code`=None
+ `lang`=None
+ `source`=None
+ `cmd`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
+ `args`=None
+ `max_output`=None
+ `concurrency`=4
Apply one code/function to each input in parallel; returns parsed JSON results
in input order. Raises with the failing index after all workers finish.
*> host_foreign_call_many inputs=`inputs` code=`code` lang=`lang` source=`source` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output` concurrency=`concurrency`*
## session_open
+ `lang`
+ `cmd`=None
+ `env`=None
+ `cwd`=None
+ `timeout`=None
Start a persistent Python/Node kernel; returns a session id. `timeout` is the
default per-eval timeout.
*> host_foreign_session_open lang=`lang` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout`*
## session_eval
+ `id`
+ `code`=None
+ `source`=None
+ `input`=None
+ `timeout`=None
Evaluate code (a code value) or source text in session id; returns a record
with id/alive. `input` is JSON-encoded for the kernel.
*> host_foreign_session_eval id=`id` code=`code` source=`source` input=`input` timeout=`timeout`*
## session_set
+ `id`
+ `name`
+ `value`
Set one kernel variable from a Marqdo value (JSON copy).
*> host_foreign_session_set id=`id` name=`name` value=`value`*
## session_get
+ `id`
+ `name`
Read one kernel variable as a Marqdo value.
*> host_foreign_session_get id=`id` name=`name`*
## session_names
+ `id`
List kernel variable names.
*> host_foreign_session_names id=`id`*
## session_close
+ `id`
Kill and remove a session; returns whether it existed.
*> host_foreign_session_close id=`id`*
## session_list
List live sessions with id/lang/cmd/evals/alive/started_ms.
*> host_foreign_session_list*
## langs
+2 -2
View File
@@ -11,7 +11,7 @@ Persist run output in .mq.md (Jupyter-style writeback)
+ `key`=None
+ `line`=None
Write `value` to `<!-- marqdo-out … -->` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
Write `value` into the entry file. Image-like values (`.png` / `.svg` / … or `data:image/…`) become `![marqdo-out](…)` (or `![marqdo-out key](…)`); other values use `<!-- marqdo-out … -->`. Default: insert or replace the block immediately below the call; `at_end=true` replaces the unkeyed EOF block. With `key=` (e.g. `ok` / `error`), replace or create that named slot only — slots do not overwrite each other. Optional `line=` anchors the block under that source line (needed when writing from a subtask).
*> host_writeback_record value=`value` at_end=`at_end` key=`key` line=`line`*
@@ -51,6 +51,6 @@ List all output blocks in the entry file (includes `key` when named).
## scan_path
+ `path`
List `<!-- marqdo-out … -->` slots in any file (workbook inspection).
List writeback slots in any file (HTML comment and `![marqdo-out](…)` image forms; workbook inspection).
*> host_writeback_scan_path path=`path`*
+180 -6
View File
@@ -8,29 +8,203 @@ description: 通过本机解释器运行绑定的代码围栏与内联源码
## 设置命令
+ `语言`
+ `命令`
+ `参数`=None
为语言绑定解释器命令。
为语言绑定解释器命令;可选附加参数。
*> host_foreign_set_cmd lang=`语言` cmd=`命令`*
*> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`*
## 运行
+ `代码`
+ `标准输入`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
+ `参数`=None
+ `最大输出`=None
运行已绑定的代码围栏值;可选标准输入。
运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、
附加参数与输出上限。返回 stdout 文本;非 0 退出即报错。
调用例:[外联.运行] 代码=`块`
*> host_foreign_run code=`代码` stdin=`标准输入`*
*> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`*
## 按语言运行
+ `语言`
+ `源码`
+ `标准输入`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
+ `参数`=None
+ `最大输出`=None
用语言运行源码文本;可选标准输入。
用语言运行源码文本;选项同“运行”。
*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入`*
*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`*
## 执行
+ `代码`=None
+ `语言`=None
+ `源码`=None
+ `标准输入`=None
+ `输入`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
+ `参数`=None
+ `输出`=auto
+ `最大输出`=None
+ `命令`=None
+ `保留`=False
运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错。
字段:ok、code、stdout、stderr、ms、lang、cmd、timed_out、truncated、
result、result_error、error、script、cached。
`输入` 会编码为 JSON 写入 stdin(与 `标准输入` 互斥)。`输出` 可取
auto | text | json | lines。`命令` 仅本次覆盖解释器。
*> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`*
## 探测
+ `语言`=None
探测一个语言;省略语言时探测所有已知语言。返回
{lang, cmd, path, ok, version, error}(省略语言时是列表)。
*> host_foreign_probe lang=`语言`*
## 注册
+ `语言`
+ `命令`=None
+ `参数`=None
+ `模板`=None
+ `扩展名`=None
+ `环境`=None
+ `版本参数`=None
注册语言调用。提供命令(+参数)或模板(占位符
{file}、{dir}、{base}、{inline}、{lang}、{cwd});二者互斥。
*> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`*
## 注销
+ `语言`
移除进程内注册;预设 / 配置 / 环境变量仍然生效。
*> host_foreign_unset lang=`语言`*
## 加载配置
+ `路径`=None
加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量。
*> host_foreign_load_config path=`路径`*
## 调用
+ `代码`=None
+ `语言`=None
+ `源码`=None
+ `输入`=None
+ `标准输入`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
+ `参数`=None
JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回值
(stdout 为空 → None)。进程失败或 JSON 非法时报错。
*> host_foreign_call code=`代码` lang=`语言` source=`源码` input=`输入` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数`*
## 批量运行
+ `任务表`
+ `并发`=4
并行运行一组代码值或 invoke 选项 map;按输入顺序返回记录。单项失败不影响其它项。
*> host_foreign_run_many runs=`任务表` concurrency=`并发`*
## 批量调用
+ `输入表`
+ `代码`=None
+ `语言`=None
+ `源码`=None
+ `命令`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
+ `参数`=None
+ `最大输出`=None
+ `并发`=4
把同一段代码并行作用到每个输入;按输入顺序返回解析后的 JSON 结果。
全部结束后若任一项失败,报错并指出下标。
*> host_foreign_call_many inputs=`输入表` code=`代码` lang=`语言` source=`源码` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出` concurrency=`并发`*
## 会话开启
+ `语言`
+ `命令`=None
+ `环境`=None
+ `工作目录`=None
+ `超时`=None
启动一个持久的 Python / Node 内核;返回会话 id。`超时` 是每次求值的默认超时。
*> host_foreign_session_open lang=`语言` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时`*
## 会话求值
+ `标识`
+ `代码`=None
+ `源码`=None
+ `输入`=None
+ `超时`=None
在会话中求值代码(code 值)或源码文本;返回带 id/alive 的记录。
`输入` 会编码为 JSON 交给内核。
*> host_foreign_session_eval id=`标识` code=`代码` source=`源码` input=`输入` timeout=`超时`*
## 会话设值
+ `标识`
+ `名称`
+ `值`
把一个 Marqdo 值写入内核变量(JSON 拷贝)。
*> host_foreign_session_set id=`标识` name=`名称` value=`值`*
## 会话取值
+ `标识`
+ `名称`
把一个内核变量读成 Marqdo 值。
*> host_foreign_session_get id=`标识` name=`名称`*
## 会话变量
+ `标识`
列出内核变量名。
*> host_foreign_session_names id=`标识`*
## 会话关闭
+ `标识`
终止并移除会话;返回是否存在。
*> host_foreign_session_close id=`标识`*
## 会话表
列出活动会话的 id/lang/cmd/evals/alive/started_ms。
*> host_foreign_session_list*
## 语言表
+2 -2
View File
@@ -11,7 +11,7 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
+ `键`=None
+ `行`=None
在入口文件中写入 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
在入口文件中写入自写回块:若 `值` 像图片路径/URL(`.png` / `.svg` / … 或 `data:image/…`)则写成 `![marqdo-out](…)`,否则写成 `<!-- marqdo-out … -->`。默认在调用行下方插入或替换;`末尾=true` 时替换无键末尾块。带 `键=`(如 `ok` / `error` / `成功` / `失败`)时只更新该命名槽,互不覆盖。可选 `行=` 锚定到指定源码行(子任务写回时需要)。
*> host_writeback_record value=`值` at_end=`末尾` key=`键` line=`行`*
@@ -51,6 +51,6 @@ description: 将运行结果写回 .mq.md(Jupyter 式自写回)
## 扫描路径
+ `路径`
扫描任意文件中的 `<!-- marqdo-out … -->` 槽(工作簿观察)。
扫描任意文件中的自写回槽(注释块与 `![marqdo-out](…)` 图片;工作簿观察)。
*> host_writeback_scan_path path=`路径`*
+170 -1
View File
@@ -511,11 +511,25 @@ fn write_skill_concept(
quality: i64,
hits: i64,
now: &str,
meta: &SkillMeta,
) -> Result<(), String> {
if let Some(p) = path.parent() {
fs::create_dir_all(p).map_err(|e| format!("mkdir: {e}"))?;
}
let title: String = goal.chars().take(48).collect();
let mut extra = String::new();
if let Some(ref s) = meta.applies_when {
extra.push_str(&format!("applies_when: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.fixtures {
extra.push_str(&format!("fixtures: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.sandbox_profile {
extra.push_str(&format!("sandbox_profile: {}\n", yaml_escape(s)));
}
if let Some(ref s) = meta.proof {
extra.push_str(&format!("proof: {}\n", yaml_escape(s)));
}
let body = format!(
r#"---
type: Marqdo Agent Skill
@@ -526,7 +540,7 @@ status: {status}
llm_free: {llm_free}
quality: {quality}
hits: {hits}
generated:
{extra}generated:
by: marqdo-agent/plan
at: {now}
verified:
@@ -545,11 +559,29 @@ Prefer spawning `resource` over re-planning.
llm_free = if llm_free { "true" } else { "false" },
quality = quality,
hits = hits,
extra = extra,
now = now,
);
fs::write(path, body).map_err(|e| format!("write skill: {e}"))
}
#[derive(Default)]
struct SkillMeta {
applies_when: Option<String>,
fixtures: Option<String>,
sandbox_profile: Option<String>,
proof: Option<String>,
}
fn skill_meta_from_src(src: &str) -> SkillMeta {
SkillMeta {
applies_when: extract_fm_field(src, "applies_when"),
fixtures: extract_fm_field(src, "fixtures"),
sandbox_profile: extract_fm_field(src, "sandbox_profile"),
proof: extract_fm_field(src, "proof"),
}
}
fn refresh_index(root: &Path, slug: &str, goal: &str) -> Result<(), String> {
let index = root.join("index.md");
let line = format!(
@@ -585,6 +617,10 @@ fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
.ok_or_else(|| format!("missing text `{key}`"))
}
fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
args.get(key).and_then(|v| v.as_str()).filter(|s| !s.is_empty())
}
fn opt_tools(args: &Value) -> Option<&Value> {
args.get("tools").filter(|t| !t.is_null())
}
@@ -1107,6 +1143,54 @@ pub fn kb_record_hit(args: &Value) -> Result<Value, String> {
}))
}
/// Run workbook (or FM `proof:` / `fixtures:` path) inside CoW sandbox; discard after.
/// O2: llm_free promote requires this proof to succeed (unless `require_proof=false`).
fn sandbox_proof(workbook: &Path, proof_rel: Option<&str>) -> Result<(bool, String), String> {
let root = workbook
.parent()
.ok_or_else(|| "sandbox_proof: workbook has no parent".to_string())?;
// Always pass an absolute root so host `sandbox_open` does not re-join cwd.
let root_abs = if root.is_absolute() {
root.to_path_buf()
} else {
fs::canonicalize(root).unwrap_or_else(|_| {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(root)
})
};
let root_abs = fs::canonicalize(&root_abs).unwrap_or(root_abs);
let default_name = workbook
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| "sandbox_proof: bad workbook name".to_string())?;
let path = proof_rel.unwrap_or(default_name);
let open = crate::host_query_json_args(
"sandbox_open",
&json!({ "root": root_abs.to_string_lossy() }),
)?;
let id = open
.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_proof: open missing id".to_string())?
.to_string();
let run = crate::host_query_json_args("sandbox_run", &json!({ "id": id, "path": path }));
let _ = crate::host_query_json_args("sandbox_discard", &json!({ "id": id }));
match run {
Ok(r) => {
let ok = r.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
let detail = r
.get("stderr")
.and_then(|v| v.as_str())
.or_else(|| r.get("stdout").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
Ok((ok, detail))
}
Err(e) => Ok((false, e)),
}
}
pub fn kb_promote(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let goal = arg_text(args, "goal")?;
@@ -1119,6 +1203,26 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
let src_path = resolve_path(workbook);
let src = fs::read_to_string(&src_path)
.map_err(|e| format!("kb_promote read workbook: {e}"))?;
let require_proof = args
.get("require_proof")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let proof_rel = extract_fm_field(&src, "proof")
.or_else(|| extract_fm_field(&src, "fixtures"));
if require_proof {
let (ok, detail) = sandbox_proof(&src_path, proof_rel.as_deref())?;
if !ok {
return Ok(json!({
"promoted": false,
"reason": "sandbox_proof_failed",
"detail": detail,
"sig": sig,
"slug": slug,
"workbook": workbook,
"proof": proof_rel.unwrap_or_else(|| src_path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_string()),
}));
}
}
let (llm_free, quality) = llm_free_score(&src);
let status = if llm_free { "stable" } else { "candidate" };
@@ -1168,6 +1272,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
&now,
&extra_aliases,
)?;
let meta = skill_meta_from_src(&src);
write_skill_concept(
&skill_path,
&sig,
@@ -1178,6 +1283,7 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
quality,
prev_hits,
&now,
&meta,
)?;
refresh_index(&root, &slug, &goal_n)?;
@@ -1190,6 +1296,69 @@ pub fn kb_promote(args: &Value) -> Result<Value, String> {
"quality": quality,
"status": status,
"hits": prev_hits,
"proof_ok": true,
"applies_when": meta.applies_when,
"fixtures": meta.fixtures,
"sandbox_profile": meta.sandbox_profile,
}))
}
/// O5: mark a skill concept as `status: quarantine` and keep fixtures path in FM.
pub fn kb_quarantine(args: &Value) -> Result<Value, String> {
let kb = arg_text(args, "kb_dir")?;
let slug = arg_text(args, "slug")?;
let reason = opt_text(args, "reason").unwrap_or("sandbox_or_harness_failed");
let root = resolve_path(kb);
let skill_path = root.join("concepts/skills").join(format!("{slug}.md"));
if !skill_path.is_file() {
return Ok(json!({
"ok": false,
"reason": "skill_not_found",
"slug": slug,
"path": skill_path.to_string_lossy(),
}));
}
let src = fs::read_to_string(&skill_path)
.map_err(|e| format!("kb_quarantine read: {e}"))?;
let mut lines: Vec<String> = Vec::new();
let mut saw_status = false;
let mut in_fm = false;
for line in src.lines() {
let t = line.trim();
if t == "---" {
if !in_fm {
in_fm = true;
lines.push(line.to_string());
continue;
} else {
if !saw_status {
lines.push("status: quarantine".to_string());
}
lines.push(format!("quarantine_reason: {}", yaml_escape(reason)));
in_fm = false;
lines.push(line.to_string());
continue;
}
}
if in_fm && t.starts_with("status:") {
lines.push("status: quarantine".to_string());
saw_status = true;
continue;
}
if in_fm && t.starts_with("llm_free:") {
lines.push("llm_free: false".to_string());
continue;
}
lines.push(line.to_string());
}
let body = lines.join("\n") + "\n";
fs::write(&skill_path, body).map_err(|e| format!("kb_quarantine write: {e}"))?;
Ok(json!({
"ok": true,
"slug": slug,
"status": "quarantine",
"reason": reason,
"path": skill_path.to_string_lossy(),
}))
}
+39
View File
@@ -8,6 +8,7 @@ mod mcp_server;
mod memory;
mod resume;
mod route;
mod sandbox;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
@@ -900,6 +901,7 @@ kb_ffi!(agent_corpus_search, corpus::corpus_search, "agent_corpus_search");
kb_ffi!(agent_mcp_fixture, corpus::mcp_fixture, "agent_mcp_fixture");
kb_ffi!(agent_kb_add_alias, kb::kb_add_alias, "agent_kb_add_alias");
kb_ffi!(agent_kb_promote, kb::kb_promote, "agent_kb_promote");
kb_ffi!(agent_kb_quarantine, kb::kb_quarantine, "agent_kb_quarantine");
kb_ffi!(agent_kb_record_hit, kb::kb_record_hit, "agent_kb_record_hit");
kb_ffi!(
agent_workbook_solidify,
@@ -1066,6 +1068,15 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{
return 1;
}
if register(
host,
"agent_kb_quarantine",
"kb_dir,slug",
agent_kb_quarantine,
) != 0
{
return 1;
}
if register(host, "agent_kb_record_hit", "kb_dir,goal", agent_kb_record_hit) != 0 {
return 1;
}
@@ -1180,6 +1191,34 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
{
return 1;
}
// Optional JSON keys only — empty params CSV so omitted args are not required.
if register(host, "sandbox_open", "", sandbox::sandbox_open) != 0 {
return 1;
}
if register(host, "sandbox_write", "", sandbox::sandbox_write) != 0 {
return 1;
}
if register(host, "sandbox_read", "", sandbox::sandbox_read) != 0 {
return 1;
}
if register(host, "sandbox_remove", "", sandbox::sandbox_remove) != 0 {
return 1;
}
if register(host, "sandbox_diff", "", sandbox::sandbox_diff) != 0 {
return 1;
}
if register(host, "sandbox_commit", "", sandbox::sandbox_commit) != 0 {
return 1;
}
if register(host, "sandbox_discard", "", sandbox::sandbox_discard) != 0 {
return 1;
}
if register(host, "sandbox_inspect", "", sandbox::sandbox_inspect) != 0 {
return 1;
}
if register(host, "sandbox_run", "", sandbox::sandbox_run) != 0 {
return 1;
}
0
}
+336 -41
View File
@@ -1,9 +1,14 @@
//! Minimal MCP Server (stdio JSON-RPC) — tools map to `lib.member` via host `call_lib_path`.
//! Minimal MCP Server — stdio JSON-RPC + Streamable HTTP (spec 2025-03-26).
use serde_json::{json, Map, Value};
use std::ffi::CStr;
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::os::raw::{c_char, c_int};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::{host_query_json_args, parse_args, set_err, set_out};
@@ -98,6 +103,40 @@ fn call_tool(tools: &[Value], name: &str, arguments: &Value) -> Result<Value, St
}))
}
/// Handle one JSON-RPC message. Returns `None` for notifications (no response body).
fn dispatch_rpc(name: &str, tools: &[Value], msg: &Value) -> Option<Value> {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or("");
let params = msg.get("params").cloned().unwrap_or(json!({}));
if matches!(id, Value::Null) && method.starts_with("notifications/") {
return None;
}
Some(match method {
"initialize" => rpc_result(
&id,
json!({
"protocolVersion": "2025-03-26",
"capabilities": { "tools": {} },
"serverInfo": { "name": name, "version": "0.1.0" }
}),
),
"tools/list" | "list_tools" => rpc_result(&id, tools_list(tools)),
"tools/call" | "call_tool" => {
let tname = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match call_tool(tools, tname, &args) {
Ok(r) => rpc_result(&id, r),
Err(e) => rpc_error(&id, -32000, &e),
}
}
"ping" => rpc_result(&id, json!({})),
"" => rpc_error(&id, -32600, "missing method"),
other => rpc_error(&id, -32601, &format!("method not found: {other}")),
})
}
/// Blocking stdio MCP loop. `tools` is a JSON array of `{name, fn, description}`.
pub fn serve_stdio(name: &str, tools: Vec<Value>) -> Result<Value, String> {
let stdin = std::io::stdin();
@@ -106,41 +145,274 @@ pub fn serve_stdio(name: &str, tools: Vec<Value>) -> Result<Value, String> {
let Some(msg) = read_line_message(&mut reader)? else {
break;
};
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or("");
let params = msg.get("params").cloned().unwrap_or(json!({}));
if matches!(id, Value::Null) && method.starts_with("notifications/") {
continue;
if let Some(reply) = dispatch_rpc(name, &tools, &msg) {
write_message(&reply)?;
}
let reply_msg = match method {
"initialize" => rpc_result(
&id,
json!({
"protocolVersion": "2024-11-05",
"capabilities": { "tools": {} },
"serverInfo": { "name": name, "version": "0.1.0" }
}),
),
"tools/list" | "list_tools" => rpc_result(&id, tools_list(&tools)),
"tools/call" | "call_tool" => {
let tname = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match call_tool(&tools, tname, &args) {
Ok(r) => rpc_result(&id, r),
Err(e) => rpc_error(&id, -32000, &e),
}
}
"ping" => rpc_result(&id, json!({})),
"" => rpc_error(&id, -32600, "missing method"),
other => rpc_error(&id, -32601, &format!("method not found: {other}")),
};
write_message(&reply_msg)?;
}
Ok(json!({ "ok": true, "transport": "stdio" }))
}
fn new_session_id() -> String {
static SEQ: AtomicU64 = AtomicU64::new(1);
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
format!("mcp-{ms}-{n}")
}
fn read_http_request(
reader: &mut BufReader<TcpStream>,
) -> Result<(String, String, Vec<(String, String)>, Vec<u8>), String> {
let mut request_line = String::new();
reader
.read_line(&mut request_line)
.map_err(|e| format!("read request: {e}"))?;
let parts: Vec<&str> = request_line.trim().split_whitespace().collect();
if parts.len() < 2 {
return Err("bad request line".into());
}
let method = parts[0].to_string();
let path = parts[1].to_string();
let mut headers = Vec::new();
let mut content_length = 0usize;
loop {
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|e| format!("read header: {e}"))?;
let line = line.trim_end_matches(['\r', '\n']);
if line.is_empty() {
break;
}
if let Some((k, v)) = line.split_once(':') {
let key = k.trim().to_string();
let val = v.trim().to_string();
if key.eq_ignore_ascii_case("content-length") {
content_length = val.parse().unwrap_or(0);
}
headers.push((key, val));
}
}
let mut body = vec![0u8; content_length];
if content_length > 0 {
reader
.read_exact(&mut body)
.map_err(|e| format!("read body: {e}"))?;
}
Ok((method, path, headers, body))
}
fn header_get<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
fn write_http(
stream: &mut TcpStream,
status: u16,
reason: &str,
content_type: &str,
body: &[u8],
extra: &[(&str, &str)],
) -> Result<(), String> {
let mut head = format!(
"HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n",
body.len()
);
for (k, v) in extra {
head.push_str(k);
head.push_str(": ");
head.push_str(v);
head.push_str("\r\n");
}
head.push_str("\r\n");
stream
.write_all(head.as_bytes())
.map_err(|e| e.to_string())?;
stream.write_all(body).map_err(|e| e.to_string())?;
stream.flush().map_err(|e| e.to_string())?;
Ok(())
}
fn path_matches(req_path: &str, endpoint: &str) -> bool {
let base = req_path.split('?').next().unwrap_or(req_path);
base == endpoint || base.trim_end_matches('/') == endpoint.trim_end_matches('/')
}
fn handle_http_conn(
stream: TcpStream,
name: &str,
tools: &[Value],
endpoint: &str,
) -> Result<(), String> {
let mut reader = BufReader::new(stream);
let (method, path, headers, body) = read_http_request(&mut reader)?;
let mut stream = reader.into_inner();
if !path_matches(&path, endpoint) {
write_http(
&mut stream,
404,
"Not Found",
"application/json",
br#"{"error":"not_found"}"#,
&[],
)?;
return Ok(());
}
if method.eq_ignore_ascii_case("GET") {
// Optional SSE stream — empty keepalive then close (clients may 405).
let accept = header_get(&headers, "Accept").unwrap_or("");
if accept.contains("text/event-stream") {
let body = b": mcp streamable-http ready\n\n";
write_http(
&mut stream,
200,
"OK",
"text/event-stream",
body,
&[("Cache-Control", "no-cache")],
)?;
} else {
write_http(
&mut stream,
405,
"Method Not Allowed",
"application/json",
br#"{"error":"use_post_for_jsonrpc"}"#,
&[("Allow", "POST, GET")],
)?;
}
return Ok(());
}
if method.eq_ignore_ascii_case("DELETE") {
write_http(&mut stream, 200, "OK", "application/json", b"{}", &[])?;
return Ok(());
}
if !method.eq_ignore_ascii_case("POST") {
write_http(
&mut stream,
405,
"Method Not Allowed",
"application/json",
br#"{"error":"method_not_allowed"}"#,
&[("Allow", "POST, GET, DELETE")],
)?;
return Ok(());
}
let text = String::from_utf8_lossy(&body);
let msg: Value = serde_json::from_str(text.trim()).map_err(|e| format!("json-rpc: {e}"))?;
let is_init = msg.get("method").and_then(|v| v.as_str()) == Some("initialize");
let existing_sid = header_get(&headers, "Mcp-Session-Id")
.or_else(|| header_get(&headers, "MCP-Session-Id"))
.map(|s| s.to_string());
// Notifications → 202 Accepted, empty body.
if msg.get("id").is_none() || msg.get("id") == Some(&Value::Null) {
if let Some(m) = msg.get("method").and_then(|v| v.as_str()) {
if m.starts_with("notifications/") {
write_http(
&mut stream,
202,
"Accepted",
"application/json",
b"",
&[],
)?;
return Ok(());
}
}
}
let reply = match dispatch_rpc(name, tools, &msg) {
Some(r) => r,
None => {
write_http(
&mut stream,
202,
"Accepted",
"application/json",
b"",
&[],
)?;
return Ok(());
}
};
let body = serde_json::to_vec(&reply).map_err(|e| e.to_string())?;
let mut extras: Vec<(&str, String)> = Vec::new();
if is_init {
let sid = existing_sid.unwrap_or_else(new_session_id);
extras.push(("Mcp-Session-Id", sid));
} else if let Some(sid) = existing_sid {
extras.push(("Mcp-Session-Id", sid));
}
let extra_refs: Vec<(&str, &str)> = extras.iter().map(|(k, v)| (*k, v.as_str())).collect();
write_http(
&mut stream,
200,
"OK",
"application/json",
&body,
&extra_refs,
)?;
Ok(())
}
/// Streamable HTTP MCP (POST JSON-RPC + optional GET SSE). Spec 2025-03-26.
pub fn serve_http(
name: &str,
tools: Vec<Value>,
host: &str,
port: u16,
path: &str,
) -> Result<Value, String> {
let addr = format!("{host}:{port}");
let listener = TcpListener::bind(&addr).map_err(|e| format!("bind {addr}: {e}"))?;
let name = Arc::new(name.to_string());
let tools = Arc::new(tools);
let endpoint = Arc::new(if path.is_empty() {
"/mcp".to_string()
} else if path.starts_with('/') {
path.to_string()
} else {
format!("/{path}")
});
eprintln!(
"mcp streamable-http listening on http://{addr}{} (POST JSON-RPC)",
&*endpoint
);
for conn in listener.incoming() {
match conn {
Ok(stream) => {
let name = Arc::clone(&name);
let tools = Arc::clone(&tools);
let endpoint = Arc::clone(&endpoint);
thread::spawn(move || {
if let Err(e) = handle_http_conn(stream, &name, &tools, &endpoint) {
eprintln!("mcp http conn: {e}");
}
});
}
Err(e) => eprintln!("mcp http accept: {e}"),
}
}
Ok(json!({
"ok": true,
"transport": "http",
"host": host,
"port": port,
"path": *endpoint
}))
}
pub fn tools_from_value(v: &Value) -> Vec<Value> {
if let Some(arr) = v.as_array() {
return arr.clone();
@@ -180,13 +452,6 @@ pub unsafe extern "C" fn agent_mcp_serve(
.get("transport")
.and_then(|v| v.as_str())
.unwrap_or("stdio");
if transport != "stdio" {
set_err(
err_msg,
&format!("mcp serve: transport `{transport}` not implemented yet (use stdio)"),
);
return 1;
}
let name = args
.get("name")
.and_then(|v| v.as_str())
@@ -195,7 +460,38 @@ pub unsafe extern "C" fn agent_mcp_serve(
.get("tools")
.map(tools_from_value)
.unwrap_or_default();
match serve_stdio(name, tools) {
let result = match transport {
"stdio" => serve_stdio(name, tools),
"http" | "streamable-http" | "sse" => {
let host = args
.get("host")
.and_then(|v| v.as_str())
.unwrap_or("127.0.0.1");
let port = args
.get("port")
.and_then(|v| {
v.as_u64()
.or_else(|| v.as_i64().map(|n| n as u64))
.or_else(|| v.as_str().and_then(|s| s.parse().ok()))
})
.unwrap_or(7434) as u16;
let path = args
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("/mcp");
serve_http(name, tools, host, port, path)
}
other => {
set_err(
err_msg,
&format!("mcp serve: transport `{other}` not supported (use stdio|http)"),
);
return 1;
}
};
match result {
Ok(v) => {
set_out(out_json, &v.to_string());
0
@@ -207,6 +503,5 @@ pub unsafe extern "C" fn agent_mcp_serve(
}
}
// Silence unused import if CStr unused in this module.
#[allow(dead_code)]
fn _unused(_: &CStr) {}
+26
View File
@@ -1038,10 +1038,17 @@ pub fn resolve_task(args: &Value) -> Result<Value, String> {
"tools": args.get("tools").cloned().unwrap_or(Value::Null),
}))?;
if hit.is_null() {
// Keep field set aligned with hit path so facades can safely read llm_free
// (qdagent / agent.run crashed on missing key when OKF is cold).
return Ok(json!({
"mode": "unknown",
"match": null,
"skill": null,
"resource": null,
"slug": null,
"status": null,
"llm_free": false,
"score": null,
"confidence": 0.0,
}));
}
@@ -1078,6 +1085,25 @@ pub fn resolve_task(args: &Value) -> Result<Value, String> {
mod tests {
use super::*;
#[test]
fn resolve_miss_includes_llm_free() {
let dir = std::env::temp_dir().join(format!(
"marqdo-resolve-miss-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let out = resolve_task(&json!({
"task": "no-such-skill-cold-miss",
"kb_dir": dir.to_string_lossy(),
"near_match": false,
}))
.unwrap();
assert_eq!(out.get("mode").and_then(|v| v.as_str()), Some("unknown"));
assert_eq!(out.get("llm_free").and_then(|v| v.as_bool()), Some(false));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn record_and_cluster_and_compile() {
let dir = std::env::temp_dir().join(format!(
+53
View File
@@ -0,0 +1,53 @@
//! Forward `sandbox_*` plugin calls to host_query (CoW lives in the host).
use super::{
host_query_json_args, parse_args, set_err, set_out,
};
use std::os::raw::c_char;
fn forward(
query_name: &str,
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
let v = match parse_args(args_json) {
Ok(v) => v,
Err(e) => {
set_err(err_msg, &format!("{query_name}: {e}"));
return 1;
}
};
match host_query_json_args(query_name, &v) {
Ok(j) => {
set_out(out_json, &j.to_string());
0
}
Err(e) => {
set_err(err_msg, &e);
1
}
}
}
macro_rules! sandbox_ffi {
($fn_name:ident, $query:expr) => {
pub unsafe extern "C" fn $fn_name(
args_json: *const c_char,
out_json: *mut *mut c_char,
err_msg: *mut *mut c_char,
) -> i32 {
forward($query, args_json, out_json, err_msg)
}
};
}
sandbox_ffi!(sandbox_open, "sandbox_open");
sandbox_ffi!(sandbox_write, "sandbox_write");
sandbox_ffi!(sandbox_read, "sandbox_read");
sandbox_ffi!(sandbox_remove, "sandbox_remove");
sandbox_ffi!(sandbox_diff, "sandbox_diff");
sandbox_ffi!(sandbox_commit, "sandbox_commit");
sandbox_ffi!(sandbox_discard, "sandbox_discard");
sandbox_ffi!(sandbox_inspect, "sandbox_inspect");
sandbox_ffi!(sandbox_run, "sandbox_run");
+42 -6
View File
@@ -245,7 +245,12 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
let status = r.status();
if status != 200 {
let text = read_limited(r.into_reader())?;
return Err(format!("HTTP {status}: {text}"));
return Ok(json!({
"events": [{"type": "error", "message": format!("HTTP {status}: {text}")}],
"finish": "error",
"error": format!("HTTP {status}: {text}"),
"transport": "plugin",
}));
}
let events = parse_sse_events(BufReader::new(r.into_reader()), echo)?;
Ok(json!({
@@ -256,9 +261,19 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
}
Err(ureq::Error::Status(code, r)) => {
let text = read_limited(r.into_reader()).unwrap_or_default();
Err(format!("HTTP {code}: {text}"))
Ok(json!({
"events": [{"type": "error", "message": format!("HTTP {code}: {text}")}],
"finish": "error",
"error": format!("HTTP {code}: {text}"),
"transport": "plugin",
}))
}
Err(e) => Err(format!("http POST sse {url}: {e}")),
Err(e) => Ok(json!({
"events": [{"type": "error", "message": format!("http POST sse {url}: {e}")}],
"finish": "error",
"error": format!("http POST sse {url}: {e}"),
"transport": "plugin",
})),
}
} else {
match req.send_string(&body) {
@@ -266,7 +281,14 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
let status = r.status();
let text = read_limited(r.into_reader())?;
if status != 200 {
return Err(format!("HTTP {status}: {text}"));
return Ok(json!({
"text": "",
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
"finish": "error",
"error": format!("HTTP {status}: {text}"),
"tool_calls": [],
"transport": "plugin",
}));
}
let data: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
let msg = data
@@ -299,9 +321,23 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
}
Err(ureq::Error::Status(code, r)) => {
let text = read_limited(r.into_reader()).unwrap_or_default();
Err(format!("HTTP {code}: {text}"))
Ok(json!({
"text": "",
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
"finish": "error",
"error": format!("HTTP {code}: {text}"),
"tool_calls": [],
"transport": "plugin",
}))
}
Err(e) => Err(format!("http POST {url}: {e}")),
Err(e) => Ok(json!({
"text": "",
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
"finish": "error",
"error": format!("http POST {url}: {e}"),
"tool_calls": [],
"transport": "plugin",
})),
}
}
}
+64 -1
View File
@@ -3,6 +3,7 @@ package httpx
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
@@ -118,12 +119,74 @@ func jsonWrapInvokeValue(value any) (int, map[string]any, error) {
}
switch t := value.(type) {
case map[string]any:
return http.StatusOK, t, nil
code := http.StatusOK
if ok, has := t["ok"]; has {
if b, isBool := ok.(bool); isBool && !b {
if errMsg, _ := t["error"].(string); strings.EqualFold(errMsg, "unauthorized") ||
strings.Contains(strings.ToLower(errMsg), "unauthorized") {
code = http.StatusUnauthorized
}
}
}
return code, t, nil
default:
return http.StatusOK, map[string]any{"ok": true, "result": value}, nil
}
}
// writeSSE writes OpenAI-compatible (or generic) Server-Sent Events.
// value may be a string body, or a map with key "sse" / "body" / "chunks".
func writeSSE(w http.ResponseWriter, value any) {
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher, _ := w.(http.Flusher)
writeChunk := func(s string) {
if s == "" {
return
}
if !strings.HasSuffix(s, "\n") {
s += "\n"
}
_, _ = io.WriteString(w, s)
if flusher != nil {
flusher.Flush()
}
}
switch t := value.(type) {
case string:
writeChunk(t)
case map[string]any:
if s, ok := t["sse"].(string); ok {
writeChunk(s)
return
}
if s, ok := t["body"].(string); ok {
writeChunk(s)
return
}
if chunks, ok := t["chunks"].([]any); ok {
for _, c := range chunks {
writeChunk(fmt.Sprint(c))
}
return
}
b, err := json.Marshal(t)
if err != nil {
writeChunk("data: {\"error\":\"sse_encode\"}\n\n")
return
}
writeChunk("data: " + string(b) + "\n\n")
writeChunk("data: [DONE]\n\n")
default:
writeChunk("data: " + fmt.Sprint(value) + "\n\n")
writeChunk("data: [DONE]\n\n")
}
}
func invokeArgsFromPayload(payload map[string]any) map[string]any {
args := map[string]any{}
for k, v := range payload {
+16
View File
@@ -247,6 +247,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
handler := withMiddleware(mux, mw)
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
handler = withTenant(handler, st.tenant)
handler = withStripTrailingSlash(handler)
return handler, nil
}
@@ -641,6 +642,21 @@ func withTenant(next http.Handler, cfg tenant.Config) http.Handler {
})
}
// withStripTrailingSlash rewrites request URLs so that paths like /post/foo/
// are routed as /post/foo. The root path "/" is left unchanged.
func withStripTrailingSlash(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if len(path) > 1 && path[len(path)-1] == '/' {
r.URL.Path = strings.TrimRight(path, "/")
if r.URL.Path == "" {
r.URL.Path = "/"
}
}
next.ServeHTTP(w, r)
})
}
func withMiddleware(next http.Handler, mw middleware.Config) http.Handler {
h := next
if mw.BodyLimit != nil && *mw.BodyLimit > 0 {
+62
View File
@@ -152,3 +152,65 @@ func TestNewHandlerIconsRedirectSitemap404(t *testing.T) {
t.Fatalf("home missing icon link: %s", rec.Body.String())
}
}
func TestTrailingSlashNormalization(t *testing.T) {
page := map[string]any{"title": "Home", "intro": "<p>home</p>"}
a := app.New(map[string]any{"page": page})
about := map[string]any{"title": "About", "intro": "<h1>About</h1>", "_route": "/about"}
var err error
a, err = app.Route(a, "/about", about)
if err != nil {
t.Fatal(err)
}
// Dynamic route: /post/{slug}
post := map[string]any{"title": "Post", "intro": "<h1>Post</h1>", "_route": "/post/{slug}"}
a, err = app.Route(a, "/post/{slug}", post)
if err != nil {
t.Fatal(err)
}
h, err := httpx.NewHandler(a, "")
if err != nil {
t.Fatal(err)
}
// Static route: /about should work with and without trailing slash.
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (no slash) code=%d body=%q", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (trailing slash) code=%d body=%q", rec.Code, rec.Body.String())
}
// Dynamic route: /post/hello should work with and without trailing slash.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello", nil))
if rec.Code != 200 {
t.Fatalf("post/hello (no slash) code=%d body=%q", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello/", nil))
if rec.Code != 200 {
t.Fatalf("post/hello (trailing slash) code=%d body=%q", rec.Code, rec.Body.String())
}
// Root path "/" should still work.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Home") {
t.Fatalf("root code=%d body=%q", rec.Code, rec.Body.String())
}
// Query string should be preserved after trailing slash strip.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/?foo=bar", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (trailing slash + query) code=%d body=%q", rec.Code, rec.Body.String())
}
}
+29 -12
View File
@@ -17,8 +17,8 @@ type artifactRoute struct {
Path string
File string
Request string // json | form | none | query
Response string // json | text | html
Auth string // role name or "" / "none"
Response string // json | text | html | sse
Auth string // role name or "" / "none" | "bearer"
}
func parseArtifactRoute(v any) artifactRoute {
@@ -57,16 +57,21 @@ func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route artifactRoute) {
if route.Auth != "" && !strings.EqualFold(route.Auth, "none") {
cookie := r.Header.Get("Cookie")
user := session.UsernameFromCookie(cookie)
if user == "" {
jsonErr(w, http.StatusUnauthorized, "auth required")
return
}
role := session.RoleFromCookie(cookie)
if role != "" && role != route.Auth && role != "admin" && role != "superadmin" {
jsonErr(w, http.StatusForbidden, "forbidden")
return
if strings.EqualFold(route.Auth, "bearer") || strings.EqualFold(route.Auth, "api_key") {
// Bearer / API-key auth is enforced inside the Endpoint `# main`
// (payload carries authorization / api_key). Do not require cookies.
} else {
cookie := r.Header.Get("Cookie")
user := session.UsernameFromCookie(cookie)
if user == "" {
jsonErr(w, http.StatusUnauthorized, "auth required")
return
}
role := session.RoleFromCookie(cookie)
if role != "" && role != route.Auth && role != "admin" && role != "superadmin" {
jsonErr(w, http.StatusForbidden, "forbidden")
return
}
}
}
@@ -115,6 +120,16 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar
payload[name] = v
}
}
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
if _, exists := payload["authorization"]; !exists {
payload["authorization"] = auth
}
}
if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" {
if _, exists := payload["api_key"]; !exists {
payload["api_key"] = key
}
}
value, err := plugin.RunArtifact(route.File, payload)
if err != nil {
@@ -131,6 +146,8 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
case "sse", "event-stream", "text/event-stream":
writeSSE(w, value)
default:
code, body, err := jsonWrapInvokeValue(value)
if err != nil {
@@ -102,6 +102,18 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
}
}
// Bind common auth / client headers for OpenAI-compatible and API-key surfaces.
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
if _, exists := payload["authorization"]; !exists {
payload["authorization"] = auth
}
}
if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" {
if _, exists := payload["api_key"]; !exists {
payload["api_key"] = key
}
}
args := invokeArgsFromPayload(payload)
value, err := plugin.CallLibPath(route.FnPath, args)
if err != nil {
@@ -114,10 +126,22 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
strings.Contains(msg, "no active host") {
code = http.StatusBadRequest
}
if strings.Contains(msg, "unauthorized") || strings.Contains(msg, "Unauthorized") {
code = http.StatusUnauthorized
}
jsonErr(w, code, msg)
return
}
// OpenAI-compatible handlers may return `{sse: "..."}` to force event-stream
// even when the route's declared return mode is json.
if m, ok := value.(map[string]any); ok {
if s, ok := m["sse"].(string); ok && strings.TrimSpace(s) != "" {
writeSSE(w, m)
return
}
}
switch route.ReturnMode {
case "text", "html", "text/html":
if value == nil {
@@ -135,6 +159,8 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
w.Header().Set("Content-Type", ct)
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, text)
case "sse", "event-stream", "text/event-stream":
writeSSE(w, value)
case "status":
if value == nil {
jsonErr(w, http.StatusInternalServerError, "null result")
+94 -52
View File
@@ -1,29 +1,112 @@
---
title: Welcome to Marqdo
description: User docs home — code is documentation (English)
description: User-docs home — code as documentation (English)
import math:lib/math.mq.md
import foreign:lib/foreign.mq.md
---
# main
Hi — thanks for reading this far. I am Marqdo’s developer. Marqdo is a language where *code is documentation, and documentation is code*: Markdown markers are the program structure, so what you read is what runs.
Hello — and welcome. I built Marqdo so that code is documentation and documentation is code: Markdown markers are the program structure, so what you read is what runs.
AI already prefers Markdown-shaped output. The idea was: why keep docs and code as two separate worlds? So Marqdo was born as a “docs are code” language. To keep every source renderable as Markdown, files use the `.mq.md` suffix. From early on we aimed for richer tooling — auto-generated YAML for OKF-style knowledge bases, even auto-generated slides — those are later goals. Happily, it already works well as a blogging tool: yes, this site is generated by Marqdo. And when AI writes Marqdo, you tend to burn fewer tokens — wallets everywhere thank you.
AI systems already favor Markdown-shaped output. That raised a simple question: why keep docs and programs as two separate artifacts? Marqdo is the answer. The `.mq.md` suffix exists so a file stays renderable as Markdown while remaining executable. Richer OKF-style YAML catalogs and even slide decks are on the roadmap; for now this site itself is generated by Marqdo — and that often saves tokens when an AI is writing with you.
The language is still young: structure markers, bilingual core names (`print` / `打印`, …), importable stdlibs (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Contribute on [GitHub](https://github.com/cflmy/marqdo).
The language is still early: structural markers, English/Chinese builtin aliases (`print` / `打印` …), an importable standard library (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Join in at [GitHub](https://github.com/cflmy/marqdo).
## Install
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
Pick one way to get the CLI:
Want a quick hello? Calls only run when they sit in the entry `# main` — `##` children are methods until something calls them. Try **greet who="marqdo"**. Names can include spaces: **greet who="marqdo user"**.
| Method | Notes |
|--------|-------|
Beyond the basics, Marqdo ships table, time, text, files, system, math, foreign, and more. Math and foreign deserve a special mention.
Write a math block and bind it with a TeX comment:
$$
% marqdo: var=f
x^2 - 2
$$
Then plot it: **_svg = math.plot formula=`f` var="x" min=-3 max=3**
Foreign lets you embed another language. Bind `hi` to a small Python block:
`hi` =
```python
print("hello-from-python")
```
Under Markdown this stays easy to read — which is the point: code as documentation, documentation as code.
One file, three surfaces.
| Surface | What it is |
|---|---|
| Document | ordinary Markdown: prose, tables, links and fenced code |
| Program | the same markers are executable: assignments, calls, returns |
| Knowledge | frontmatter, links and generated catalog entries an agent can query |
The static site you are reading is generated from these files, so the examples are not screenshots. Run the same source and you get the same page.
Foreign v2 is a good example. Probe Python, then run the bound fence:
**python = > foreign.probe lang="python"**
1. [ok](`python`)
**hello = > foreign.run code=`hi`**
> print text=`hello`
2. *
> print text="(python3 not found — install Python to run this cell)"
The same module also supports JSON calls, parallel fan-out, persistent kernels and an explicit state bridge. See [stdlib/foreign.mq.md](stdlib/foreign.mq.md) and the full Python walkthrough in [features/19-foreign-notebook.mq.md](features/19-foreign-notebook.mq.md).
A notebook is still a document. Named kernels and a cell order are ordinary bound tables:
```text
`内核表` =
| 名称 | 语言 | 说明 |
|------|------|------|
| 分析 | python | shared state |
| 复核 | python | isolated state |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | write |
| 计算指标 | 分析 | read |
| 独立复核 | 复核 | validate |
```
Live view turns that into Run All, Step, per-cell kernels, a journal and a state panel. Program mode still runs the file as one program.
Documentation becomes knowledge when it can be discovered, verified and reused. OKF supplies the portable Markdown + YAML shape; EKC projects the repository into catalog layers L0–L4, a graph and an engineering preflight. The source `.mq.md` remains the only authority; generated artifacts are marked and rebuildable.
| Loop | Question |
|---|---|
| OKF | How do people and agents share a readable knowledge page? |
| EKC | What existing capability, decision, constraint or failure should be reused before creating more? |
| Preflight | REUSE → ADAPT → CREATE |
Read [features/20-okf-ekc.mq.md](features/20-okf-ekc.mq.md) for the concepts and commands.
Welcome again — enjoy exploring Marqdo.
## greet
When we meet a visitor `who`, we **print text="Welcome, `who`!"** and close with*None*.
## install
Install the interpreter (CLI) in any of these ways:
| Way | Notes |
|------|------|
| Ubuntu PPA | `sudo add-apt-repository ppa:cflmy/marqdo` then `sudo apt install marqdo` |
| GitHub Releases | Prebuilt Windows / Linux zips at [releases](https://github.com/cflmy/marqdo/releases) |
| From source | `cargo build --release` (needs Rust) |
| GitHub Releases | Prebuilt Windows / Linux packages from [releases](https://github.com/cflmy/marqdo/releases) |
| From source | `cargo build --release` (needs a local Rust toolchain) |
Official extensions version independently of the CLI:
Official extensions update independently of the CLI:
```text
marqdo ext add web
@@ -31,44 +114,3 @@ marqdo ext add quantum
```
`ext add` tries CDN https://ext.marqdo.com first, then GitHub, then the proxy mirror. See [`features/05-extensions.mq.md`](features/05-extensions.mq.md).
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
A small function to say hello:
> greet who=marqdo
Named args can include spaces:
> greet who=marqdo user
## greet
+ `who`
> print text=Welcome, `who`!
*None*
Beyond the basics above, Marqdo also ships standard libraries: table, time, text, files, system, math, foreign, and more.
Math and foreign deserve a special mention. With the math library you can bind a formula like this:
`f` =
$$
x^2 - 2
$$
Then plot it:
**`_svg` = > math.plot formula=`f` var="x" min=-3 max=3**
The foreign library lets you call external code, for example:
`hi` =
```python
print("hello-from-python")
```
Under Markdown this stays easy to read — which is the point: Marqdo’s design is code as documentation, documentation as code.
Welcome again — enjoy exploring Marqdo.
+85 -44
View File
@@ -7,12 +7,95 @@ description: 用户文档首页 — 代码即文档(中文版)
# main
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门*代码即文档,文档即代码*的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门「代码即文档,文档即代码」的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
AI 偏爱 Markdown结构的输出。作者的念头是:何必再把文档和代码拆成两套?我们来实现一个文档即代码的语言,所以marqdo应运而生,为了确保代码一定可以被渲染,marqdo的文件后缀定义为了`.mq.md`。在开发之处我们就尝试希望更丰富的支持,自动生成一个yaml文件使得 OKF 式知识库便捷的自动配置,乃至自动生成ppt,自然这都是以后的目标了。不过相当不错的是,至少这会成为一个不错的博客工具——对,这个站点就是 Marqdo 生成的,而且AI输出的时候会节约不少token,你知道的,token烧的太多,钱包会可怜的饿瘦的。
AI 偏爱 Markdown 结构的输出。我当时的念头很简单——何必再把文档和代码拆成两套?于是有了 marqdo。为了让文件既能当文档渲染又能执行,后缀定为 `.mq.md`。更远的目标还有 OKF 式知识库的 YAML、甚至自动生成 PPT;眼下它至少已经是个不错的博客工具——对,这个站点就是 Marqdo 生成的。AI 写 `.mq.md` 时往往更省 token,钱包也会轻松一点。
语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。
English docs: [`00-welcome.mq.md`](00-welcome.mq.md)(English prose and English builtins).
想先打个招呼?调用写在入口 `# main` 里才会真的跑——子标题里的方法要等你叫到它。比如:**问候 谁="marqdo"**。名字里可以带空格:**问候 谁="marqdo user"**。
除了这些基本面,标准库里还有表、时间、文本、文件、系统、数学、外联等。我特别想提数学和外联。
比方说,直接写一块公式,并用 TeX 注释标上变量名:
$$
% marqdo: var=f
x^2 - 2
$$
接着画出来:**_svg = 数学.绘图 formula=`f` var="x" min=-3 max=3**
外联则允许嵌一段别的语言。把`hi`绑成下面这样即可:
`hi` =
```python
print("hello-from-python")
```
这些在 Markdown 里读起来仍然像文章——这就是 marqdo 想坚持的:代码即文档,文档即代码。
一份文件,三个面。
| 面 | 是什么 |
|---|---|
| 文档 | 普通 Markdown:叙述、表格、链接、围栏代码 |
| 程序 | 同一批标记可执行:赋值、调用、返回 |
| 知识 | frontmatter、链接与生成的 catalog 条目,Agent 可查询 |
你正在读的静态站就是由这些文件生成的,所以示例不是截图。运行同一份源,会得到同一页。
外联 v2 是个好例子。先探测 Python,再运行绑定围栏:
**python = > 外联.探测 语言="python"**
1. [ok](`python`)
**问候 = > 外联.运行 代码=`hi`**
> 打印 内容=`问候`
2. *
> 打印 内容="(未找到 python3 — 安装 Python 后可运行此单元)"
同一个模块还支持 JSON 调用、并行扇出、持久内核与显式状态桥。见 [stdlib/外联.mq.md](stdlib/外联.mq.md) 与完整 Python 示例 [features/19-外联Notebook.mq.md](features/19-外联Notebook.mq.md)。
Notebook 仍然是一篇文档。命名内核与单元顺序就是普通绑定表:
```text
`内核表` =
| 名称 | 语言 | 说明 |
|------|------|------|
| 分析 | python | 共享状态 |
| 复核 | python | 隔离状态 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | 写入 |
| 计算指标 | 分析 | 读取 |
| 独立复核 | 复核 | 校验 |
```
live view 会把它变成 Run All、Step、每单元内核、journal 与状态面板;Program 模式仍然把文件当单个程序运行。
文档能被发现、验证和复用时,才成为知识。OKF 提供可移植的 Markdown + YAML 形态;EKC 把仓库投影成 catalog L0–L4、图与工程 preflight。源 `.mq.md` 始终是唯一权威,生成物有标记、可重建。
| 循环 | 问题 |
|---|---|
| OKF | 人和 Agent 如何共享一页可读知识? |
| EKC | 创建之前,应该复用哪些已有能力、决策、约束与失败? |
| Preflight | REUSE → ADAPT → CREATE |
概念与命令见 [features/20-OKF与EKC.mq.md](features/20-OKF与EKC.mq.md)。
最后,再次欢迎你,尽情体验 marqdo 吧!
## 问候
见到访客`谁`时,我们 **打印 内容="欢迎,`谁`!"**,然后收束为*None*。
## 安装
解释器(CLI)任选其一:
@@ -31,45 +114,3 @@ marqdo ext add quantum
```
`ext add` 下载顺序:CDN https://ext.marqdo.com → GitHub → proxy 镜像。详见本站 [`features/05-扩展.mq.md`](features/05-扩展.mq.md)。
English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English builtins).
用一个小函数打个招呼:
> 问候 谁=marqdo
具名实参可以带空格:
> 问候 谁=marqdo user
## 问候
+ `谁`
> 打印 内容=欢迎,`谁`!
*None*
除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。
其中数学库和外联库是我要着重提到的,例如数学库,你可以通过下面的方式调用:
`f` =
$$
x^2 - 2
$$
之后让我们画个图像吧!
**`_svg` = > 数学.绘图 formula=`f` var="x" min=-3 max=3**
外联库则允许你调用外部代码,例如:
`hi` =
```python
print("hello-from-python")
```
这些代码在markdown下面都非常的易读,就像我说的,marqdo的设计思想就是代码即文档,
文档即代码。
最后,再次欢迎你,尽情体验marqdo吧!
+2
View File
@@ -11,6 +11,8 @@
| [`keywords/`](keywords/) | 关键字与 L0 内置 |
| [`stdlib/`](stdlib/) | **标准库**(导入方式 + text/表/文件/时间/系统/json/网络/数学/外联/插件/**自写回**/**子任务**;v0.1.2+ 内置于 CLI) |
| [`features/`](features/) | 特性迭代(含对象、官方 `ext/`) |
| [`features/19-foreign-notebook.mq.md`](features/19-foreign-notebook.mq.md) / [`19-外联Notebook.mq.md`](features/19-外联Notebook.mq.md) | 外联 v2 完整 Python 示例:probe / JSON call / 并行 / 持久内核 / 状态桥 / notebook |
| [`features/20-okf-ekc.mq.md`](features/20-okf-ekc.mq.md) / [`20-OKF与EKC.mq.md`](features/20-OKF与EKC.mq.md) | 代码即文档、文档即知识:OKF 形态与 EKC 工程知识编译器 |
官方扩展(非 stdlib):`ext/llm`、`ext/agent`、`ext/web`、`ext/quantum`、`ext/linalg` — 见 `features/05-*.mq.md`、`06-*.mq.md`、`07-linalg.mq.md` / `07-线性代数.mq.md` 与 `doc/design/ext-*.md`。
+4 -2
View File
@@ -5,12 +5,14 @@ description: Local browse and static export from the interpreter
# main
Milestone: `marqdo view` and `view output`.
Milestone: `marqdo view` and `view output` (v1.4.1 mid→mid annot leaders + document surface).
Local: `marqdo view public`
Static export: `marqdo view output public -o public`
Executable user docs live under `public/`. Generated HTML (`index.html` / `pages/`) is for hosting; CI publishes to `gh-pages`.
Browse Structure keeps narration, highlights executable markers, and attaches
run results (values, taken branch arms, call/loop frames). The same render path
builds this user docs site; CI publishes to `gh-pages`.
> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML.
+3 -2
View File
@@ -5,12 +5,13 @@ description: 本地浏览与静态导出由解释器生成
# main
里程碑:`marqdo view` 与 `view output`。
里程碑:`marqdo view` 与 `view output`(v1.4.1 mid→mid 标注连线 + 文档面)。
本地浏览:`marqdo view public`
静态导出:`marqdo view output public -o public`
用户可执行文档在 `public/`;生成的 HTML(`index.html` / `pages/`)供静态托管,CI 发布到 `gh-pages`。
Browse Structure 保真叙述、高亮可执行标记,并挂载运行结果(变量值、分支命中臂、调用/循环帧)。
用户站与 live view 同源渲染;CI 发布到 `gh-pages`。
> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。
+183
View File
@@ -0,0 +1,183 @@
---
title: Foreign kernels v2 — a Python analysis notebook
description: A complete Python data walkthrough with probe, JSON calls, parallel fan-out, persistent state, an explicit bridge and document-native notebook cells
import foreign:lib/foreign.mq.md
---
# main
This page is both a readable document and a runnable program. It uses the same file to show the foreign-kernel features added in v2: language probing, structured records, JSON in/out, parallel fan-out, a persistent Python kernel, and an explicit state bridge.
The data is intentionally small and deterministic, so every number below can be reproduced by running the page.
---
The input.
`orders` =
| @ | region | amount |
|---|--------|--------|
| 1 | 华东 | 120 |
| 2 | 华东 | 300 |
| 3 | 华南 | 90 |
| 4 | 华南 | 140 |
| 5 | 华北 | 220 |
| 6 | 西部 | 80 |
---
Probe Python before using it.
**python = > foreign.probe lang="python"**
> print text=[ok](`python`)
> print text=[version](`python`)
The probe record also carries `cmd`, `path` and `error`, so a site can explain a missing interpreter instead of producing a blank cell.
---
A JSON call. Python reads the table as JSON, groups it, and writes one JSON result.
`analyze` =
```python
import json
import statistics
import sys
rows = json.load(sys.stdin)
by_region = {}
for row in rows:
by_region.setdefault(row["region"], []).append(float(row["amount"]))
summary = []
for region, values in sorted(by_region.items()):
mean = statistics.mean(values)
sd = statistics.pstdev(values) or 1.0
summary.append({
"region": region,
"orders": len(values),
"total": round(sum(values), 2),
"mean": round(mean, 2),
"z_span": round((max(values) - mean) / sd, 3),
})
print(json.dumps({
"regions": summary,
"total": round(sum(float(row["amount"]) for row in rows), 2),
"count": len(rows),
}, ensure_ascii=False))
```
**result = > foreign.call code=`analyze` input=`orders`**
> print text=[count](`result`)
> print text=[total](`result`)
> print text=[region]([1]([regions](`result`)))
> print text=[mean]([1]([regions](`result`)))
A call is JSON-in / JSON-out: the table is encoded on stdin, and the final stdout value is parsed into Marqdo values.
---
The same work as a structured record. `invoke` keeps stdout, stderr, exit code and timing even when the program fails.
**record = > foreign.invoke code=`analyze` input=`orders` output="json"**
> print text=[ok](`record`)
> print text=[code](`record`)
> print text=[ms](`record`)
Here `result` is already a parsed value, while `stdout` remains available for logging.
---
Persistent Python state. The first evaluation imports a module and creates a list; the second evaluation sees both.
**session = > foreign.session_open lang="python"**
**first = > foreign.session_eval id=`session` source="import math\nvalues = [3, 4, 5]"**
**second = > foreign.session_eval id=`session` source="round(math.sqrt(sum(value * value for value in values)), 3)"**
> print text=[result](`second`)
The kernel is strict and serial: evaluations do not interleave, and a timeout kills the process group.
---
The explicit state bridge. Values cross as JSON copies, never as shared object references.
**> foreign.session_set id=`session` name="threshold" value=2.5**
**threshold = > foreign.session_get id=`session` name="threshold"**
> print text=`threshold`
**> foreign.session_close id=`session`**
No implicit mirroring: if a variable is not pushed or pulled, the other side does not see it.
---
Parallel fan-out. Every input gets its own process; failures are isolated and order is preserved.
`increment` =
```python
import json
import sys
value = json.load(sys.stdin)
print(json.dumps(value + 1))
```
`numbers` =
| value |
|-------|
| 1 |
| 2 |
| 3 |
| 4 |
**bumped = > foreign.call_many code=`increment` inputs=`numbers` concurrency=4**
> print text=`bumped`
---
A document-native notebook. Named kernels and a session table are ordinary bound data tables, not fence metadata or YAML config.
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | shared analysis |
| 复核 | python | | isolated review |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | generate orders |
| 计算指标 | 分析 | regions and totals |
| 独立复核 | 复核 | read the JSON report |
```
Live `view` renders these as cells with Run All, Step, per-cell kernel switching, a journal, dirty reload and a state panel. The same file still runs as a single program.
---
Why this stays readable.
| Layer | What the reader sees |
|---|---|
| Markdown | headings, prose, tables and fenced code |
| Program | assignments, calls and return values |
| Knowledge | frontmatter, links, task pages and generated catalog entries |
The foreign layer does not add syntax to the language. A fence is still a fence; a table is still a table.
For the lower-level API and safety defaults, read [`../../lib/foreign.mq.md`](../../lib/foreign.mq.md) and [`../../doc/design/foreign-kernel.md`](../../doc/design/foreign-kernel.md).
+183
View File
@@ -0,0 +1,183 @@
---
title: 外联内核 v2 — Python 分析 Notebook
description: 从 probe、JSON 调用、并行扇出、持久状态到显式桥与文档原生 notebook 单元的完整 Python 示例
导入 外联:lib/外联.mq.md
---
# main
这一页既是可读文档,也是可运行程序。它用同一份文件展示 v2 的外联内核能力:语言探测、结构化记录、JSON 进出、并行扇出、持久 Python 内核,以及显式状态桥。
数据故意保持小而确定,因此下面每个数字都可以通过运行本页复现。
---
输入数据。
`订单` =
| @ | 区域 | 金额 |
|---|------|------|
| 1 | 华东 | 120 |
| 2 | 华东 | 300 |
| 3 | 华南 | 90 |
| 4 | 华南 | 140 |
| 5 | 华北 | 220 |
| 6 | 西部 | 80 |
---
先探测 Python。
**python = > 外联.探测 语言="python"**
> 打印 内容=[ok](`python`)
> 打印 内容=[version](`python`)
探测记录还带 `cmd`、`path` 与 `error`,所以站点可以解释“解释器缺失”,而不是显示一个空白单元。
---
JSON 调用。Python 把表读成 JSON,按区域聚合,再写出一个 JSON 结果。
`分析` =
```python
import json
import statistics
import sys
rows = json.load(sys.stdin)
by_region = {}
for row in rows:
by_region.setdefault(row["区域"], []).append(float(row["金额"]))
summary = []
for region, values in sorted(by_region.items()):
mean = statistics.mean(values)
sd = statistics.pstdev(values) or 1.0
summary.append({
"region": region,
"orders": len(values),
"total": round(sum(values), 2),
"mean": round(mean, 2),
"z_span": round((max(values) - mean) / sd, 3),
})
print(json.dumps({
"regions": summary,
"total": round(sum(float(row["金额"]) for row in rows), 2),
"count": len(rows),
}, ensure_ascii=False))
```
**结果 = > 外联.调用 代码=`分析` 输入=`订单`**
> 打印 内容=[count](`结果`)
> 打印 内容=[total](`结果`)
> 打印 内容=[region]([1]([regions](`结果`)))
> 打印 内容=[mean]([1]([regions](`结果`)))
调用是 JSON 进 / JSON 出:表编码到 stdin,stdout 的最后一个值再解析成 Marqdo 值。
---
同样的工作也可以保留成结构化记录。`执行` 即使进程失败也保留 stdout、stderr、退出码与耗时。
**记录 = > 外联.执行 代码=`分析` 输入=`订单` 输出="json"**
> 打印 内容=[ok](`记录`)
> 打印 内容=[code](`记录`)
> 打印 内容=[ms](`记录`)
这里 `result` 已经是解析后的值,同时 `stdout` 仍可用于日志。
---
持久 Python 状态。第一次求值导入模块并创建列表;第二次求值仍能看到两者。
**会话 = > 外联.会话开启 语言="python"**
**第一次 = > 外联.会话求值 标识=`会话` 源码="import math\nvalues = [3, 4, 5]"**
**第二次 = > 外联.会话求值 标识=`会话` 源码="round(math.sqrt(sum(value * value for value in values)), 3)"**
> 打印 内容=[result](`第二次`)
内核严格串行:求值不会交错,超时会杀掉进程组。
---
显式状态桥。值以 JSON 拷贝跨越边界,永远不是共享对象引用。
**> 外联.会话设值 标识=`会话` 名称="threshold" 值=2.5**
**阈值 = > 外联.会话取值 标识=`会话` 名称="threshold"**
> 打印 内容=`阈值`
**> 外联.会话关闭 标识=`会话`**
没有隐式镜像:没有 push / pull 的变量,另一边看不到。
---
并行扇出。每个输入都有独立进程;失败互相隔离,顺序保持不变。
`加一` =
```python
import json
import sys
value = json.load(sys.stdin)
print(json.dumps(value + 1))
```
`数值` =
| value |
|-------|
| 1 |
| 2 |
| 3 |
| 4 |
**加一后 = > 外联.批量调用 代码=`加一` 输入表=`数值` 并发=4**
> 打印 内容=`加一后`
---
文档原生 Notebook。命名内核和会话表都是普通绑定数据表,不是 fence 元数据或 YAML 配置。
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | 共享分析 |
| 复核 | python | | 独立复核 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | 生成订单 |
| 计算指标 | 分析 | 区域与总额 |
| 独立复核 | 复核 | 读取 JSON 报告 |
```
live `view` 会把这些渲染成带 Run All、Step、切换内核、journal、dirty reload 和状态面板的单元。同一份文件仍可作为单个程序运行。
---
为什么它仍然可读。
| 层 | 读者看到什么 |
|---|---|
| Markdown | 标题、叙述、表格与围栏代码 |
| 程序 | 赋值、调用与返回值 |
| 知识 | frontmatter、链接、任务页与生成的 catalog 条目 |
外联层没有给语言新增语法。围栏还是围栏,表还是表。
底层 API 与安全默认值见 [`../../lib/外联.mq.md`](../../lib/外联.mq.md) 与 [`../../doc/design/foreign-kernel.md`](../../doc/design/foreign-kernel.md)。
+135
View File
@@ -0,0 +1,135 @@
---
title: 代码即文档,文档即知识 — OKF 与 EKC
description: Marqdo 如何以一份可执行源为唯一权威,把它投影成 OKF 风格知识与 Engineering Knowledge Compiler 制品
---
# main
Marqdo 的宪法是「代码即文档,文档即知识库」。`.mq.md` 不是程序截图:它同时是可读源码、可执行单元和知识页。
这个承诺只有在知识始终从源派生时才成立。OKF 提供可移植知识包的形态;EKC 提供工程化投影。二者都不成为第二份权威。
---
OKF 的形,Marqdo 的义。
OKF(Open Knowledge Format)用 Markdown + YAML frontmatter 表示知识:一页一概念、路径即身份、链接成图、强制面刻意保持很小。Marqdo 借用这个形态,但正文是可执行语法。
因此概念页可以直接指向证明它的文件:
```yaml
type: Capability
title: 持久外联内核
description: 在命名内核中运行 Python 或 Node 并保留状态
resource: public/features/19-外联Notebook.mq.md
status: stable
verified:
by: marqdo-knowledge/verify
tags:
- foreign
- notebook
```
同一页可以在编辑器里读、从 catalog 链接、被 Agent 查询,也可以直接运行。未知字段保留;未知类型降级为可读正文。概念页不是源文件的复制品。
---
哪些是生成的,哪些不是。
| 层 | 作者 | 职责 |
|---|---|---|
| 源 | 人或编码 Agent | .mq.md;唯一语义权威 |
| 目录包 | marqdo catalog | 模块、符号、能力与图投影 |
| 任务知识 | plan 晋升 | 任务、技能与可执行资源包 |
| 静态站 | marqdo view output | 人读 HTML,永远不是权威 |
生成物带 GENERATED 标记,可以删除重建;没有它们源树仍能运行。Catalog 是索引,不是语言特性。
---
EKC:Engineering Knowledge Compiler。
EKC 把仓库投影成工程知识系统,并在 Agent 写新代码前提供 preflight:
```text
.mq.md ──► EKC ──► catalog L0–L4
├─ graph
├─ context pack
└─ Agent preflight
```
| 层 | 知识 | 例子 |
|---|---|---|
| L0 Repository | 语言、规模、根目录 | 仓库总览 |
| L1 Module | imports、exports、职责 | 外联内核模块 |
| L2 Symbol | 签名、调用、指纹 | Python 分析函数 |
| L3 Capability | 工程能做什么 | 运行持久外联内核 |
| L4 Knowledge | 决策、约束、失败 | 为什么状态桥必须显式 |
图记录 implements、uses、depends_on、tested_by、documented_by、constrained_by、decided_by、supersedes、conflicts_with、deprecated_by 等关系。Agent 先沿图发现已有能力,而不是重新造轮子。
---
Engineering First Information:先发现,再创建。
复用协议是硬顺序:
```text
REUSE → ADAPT → CREATE
```
preflight 可以在实现开始前返回已有能力、API、约束、决策与失败经验。知识图缺失时返回明确的 missing_knowledge,而不是静默编造。
五条原则:
| # | 原则 |
|---|---|
| 1 | Discover before Create |
| 2 | Reuse before Adapt |
| 3 | Adapt before Duplicate |
| 4 | Verify before Promote |
| 5 | Code changes update knowledge |
---
命令。
```bash
# 把仓库投影成 catalog + EKC 制品
marqdo catalog .
# 写代码前先问:已经有了什么?
marqdo knowledge preflight "增加一个持久外联内核"
marqdo find "外联 会话"
marqdo reuse "实现 JSON 并行扇出"
# 看一次修改会影响什么
marqdo impact public/features/19-外联Notebook.mq.md
# 校验知识投影
marqdo knowledge verify
```
`marqdo catalog` 保留人读的 `index.md` 与模块页;EKC 在 `.marqdo/` 下增加 L0–L4。两者都从同一棵源树生成。
---
每个声称的能力都必须有可执行资源。
一个知识页说“这个工程能分析订单”,就必须指向一个真正能跑的 `.mq.md` 资源。这是 OKF 形态的笔记与可执行知识系统的区别。
在外联示例里,页面本身就是证明:Python 调用、持久内核和状态桥都从读者正在看的同一份 Markdown 源运行。没有另一个会漂移的演示项目。
---
继续阅读。
OKF 设计:[OKF 设计](../../doc/design/okf.md)
Engineering Knowledge Compiler:[Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md)
Catalog CLI:[Catalog CLI](../../doc/design/catalog-cli.md)
OKF 与 Marqdo 调研:[OKF 与 Marqdo 调研](../../doc/research/okf-and-marqdo.md)
外联 Notebook 示例:[外联 Notebook 示例](19-外联Notebook.mq.md)
+135
View File
@@ -0,0 +1,135 @@
---
title: Code as documentation, documentation as knowledge — OKF and EKC
description: How Marqdo keeps one executable source of truth while projecting it into OKF-style knowledge and Engineering Knowledge Compiler artifacts
---
# main
Marqdo's constitution is code as documentation and documentation as knowledge. A `.mq.md` file is not a screenshot of a program: it is the readable source, the executable unit and the knowledge page at the same time.
That claim matters only if the knowledge stays derived from the source. OKF gives us the shape of a portable knowledge bundle; EKC gives us the engineering projection. Neither becomes a second source of truth.
---
OKF shape, Marqdo meaning.
OKF (Open Knowledge Format) describes knowledge as Markdown pages with YAML frontmatter: one concept per page, path as identity, links as graph, a deliberately small required surface. Marqdo borrows that shape, but its body is executable.
A concept page can therefore point at the exact file that proves it:
```yaml
type: Capability
title: Persistent foreign kernels
description: Run Python or Node in a named, stateful kernel
resource: public/features/19-foreign-notebook.mq.md
status: stable
verified:
by: marqdo-knowledge/verify
tags:
- foreign
- notebook
```
The same page can be opened in an editor, linked from a catalog, queried by an agent, and executed. Unknown fields are preserved; unknown types degrade to readable prose. The page is a concept, not a copy of one.
---
What is generated, and what is not.
| Layer | Author | Role |
|---|---|---|
| Source | person or coding agent | .mq.md; the only semantic authority |
| Catalog | marqdo catalog | module, symbol, capability and graph projection |
| Task knowledge | plan promotion | task, skill and executable resource bundle |
| Static site | marqdo view output | human-readable HTML, never an authority |
Generated artifacts are marked GENERATED and can be deleted and rebuilt. The source tree still runs without them. A catalog is an index, not a language feature.
---
EKC: the Engineering Knowledge Compiler.
EKC projects the repository into an engineering knowledge system, then exposes it through a preflight before an agent writes new code:
```text
.mq.md ──► EKC ──► catalog L0–L4
├─ graph
├─ context pack
└─ Agent preflight
```
| Layer | Knowledge | Example |
|---|---|---|
| L0 Repository | language, size, roots | repository summary |
| L1 Module | imports, exports, responsibility | a foreign kernel module |
| L2 Symbol | signature, calls, fingerprint | a Python analysis function |
| L3 Capability | what the project can do | run a persistent foreign kernel |
| L4 Knowledge | decisions, constraints, failures | why the bridge is explicit |
The graph records relations such as implements, uses, depends_on, tested_by, documented_by, constrained_by, decided_by, supersedes, conflicts_with and deprecated_by. That graph is how an agent discovers existing capability before inventing a duplicate.
---
Engineering First Information: discover before create.
The reuse protocol is a hard order:
```text
REUSE → ADAPT → CREATE
```
A preflight can return existing capabilities, APIs, constraints, decisions and failure notes before a new implementation starts. If the knowledge graph is missing, the result is an explicit missing_knowledge state, not a silent fabrication.
The five principles are:
| # | Principle |
|---|---|
| 1 | Discover before Create |
| 2 | Reuse before Adapt |
| 3 | Adapt before Duplicate |
| 4 | Verify before Promote |
| 5 | Code changes update knowledge |
---
The commands.
```bash
# Project the repository into catalog + EKC artifacts
marqdo catalog .
# Ask what already exists before writing code
marqdo knowledge preflight "add a persistent foreign kernel"
marqdo find "foreign session"
marqdo reuse "implement JSON fan-out"
# See what a change would touch
marqdo impact public/features/19-foreign-notebook.mq.md
# Validate the knowledge projection
marqdo knowledge verify
```
`marqdo catalog` keeps the human-readable `index.md` and module pages; EKC adds L0–L4 files under `.marqdo/`. Both are generated from the same source tree.
---
Every claimed capability has an executable resource.
A knowledge page that says “this project can analyze orders” must point to a `.mq.md` resource that actually runs. That is the difference between an OKF-shaped note and an executable knowledge system.
In the foreign example, the page itself is the proof: the Python call, the persistent kernel and the state bridge all run from the same Markdown source that a reader is looking at. There is no separate demo project to drift out of sync.
---
Read more.
OKF design: [OKF design](../../doc/design/okf.md)
Engineering Knowledge Compiler: [Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md)
Catalog CLI: [Catalog CLI](../../doc/design/catalog-cli.md)
OKF and Marqdo research: [OKF and Marqdo research](../../doc/research/okf-and-marqdo.md)
Foreign notebook example: [Foreign notebook example](19-foreign-notebook.mq.md)
+1 -1
View File
@@ -11,7 +11,7 @@ English-named files export English APIs; Chinese-named files export Chinese APIs
No extra allow flags: importing a module means you intend to use it. Under marqdo view or static export, exit soft-fails and long sleeps are clamped so the console stays up.
Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络), math (math / 数学), foreign (foreign / 外联), plugin (plugin / 插件), writeback (writeback / 自写回), subtask (subtask / 子任务).
Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络), math (math / 数学), foreign (foreign / 外联), plugin (plugin / 插件), writeback (writeback / 自写回), subtask (subtask / 子任务). Foreign v2 adds structured invoke records, JSON calls, parallel fan-out, persistent Python/Node kernels, an explicit state bridge and document-native notebook sessions — see stdlib/foreign.mq.md and features/19-foreign-notebook.mq.md.
From v0.1.2, official `lib/*.mq.md` is embedded in the `marqdo` binary (disk `lib/` or `MARQDO_LIB` still overrides). Standalone `.exe` works without a separate stdlib zip.
+1 -1
View File
@@ -11,7 +11,7 @@ description: 如何导入官方 lib 模块
导入即表示要用对应能力,无需再加允许旗标。marqdo view 或静态导出里,退出会软失败、长睡眠会被钳制,以免拖垮控制台。
模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)、数学(math / 数学)、外联(foreign / 外联)、插件(plugin / 插件)、自写回(writeback / 自写回)、子任务(subtask / 子任务)。
模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)、数学(math / 数学)、外联(foreign / 外联)、插件(plugin / 插件)、自写回(writeback / 自写回)、子任务(subtask / 子任务)。外联 v2 新增结构化执行记录、JSON 调用、并行扇出、Python/Node 持久内核、显式状态桥与文档原生 notebook 会话 — 见 stdlib/外联.mq.md 与 features/19-外联Notebook.mq.md。
自 v0.1.2 起,官方 `lib/*.mq.md` 内置于 `marqdo` 二进制(磁盘 `lib/` 或 `MARQDO_LIB` 仍可覆盖)。单独下载 `.exe` 即可导入标准库,无需再解压 stdlib 包。
+134 -9
View File
@@ -1,20 +1,145 @@
---
title: lib/foreign — external languages
description: Run local interpreters from Marqdo (English)
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
---
# main
Import lib/foreign.mq.md. Bind a code fence like a formula: empty-RHS assign then a ```lang block. The value type is code. Call run code=`name` to execute via your local interpreter. run_lang runs an inline source string.
`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.
`hi` =
```python
print("hello-from-python")
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.
**node = > foreign.probe lang="node"**
> print text=[ok](`node`)
> print text=[version](`node`)
`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("hello from a foreign kernel");
```
Default command is python (Windows) or python3 (Unix). Override with set_cmd, env MARQDO_FOREIGN_PYTHON, or the command box in live view. Failures ask you to check that configuration.
**record = > foreign.invoke code=`marker`**
**`out` = [foreign.run] code=`hi`**
> print text=[ok](`record`)
> print text=[stdout](`record`)
> print text=[code](`record`)
> print text=`out`
`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.
`double` =
```node
let input = "";
process.stdin.on("data", chunk => { input += chunk; });
process.stdin.on("end", () => {
console.log(JSON.stringify(JSON.parse(input) * 2));
});
```
**single = > foreign.call code=`double` input=21**
> 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 |
**doubled = > foreign.call_many code=`double` inputs=`numbers` concurrency=4**
> print text=`doubled`
`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.
**session = > foreign.session_open lang="node"**
**first = > foreign.session_eval id=`session` source="let total = 0; for (let i = 1; i <= 5; i += 1) total += i;"**
**second = > foreign.session_eval id=`session` source="total * 2"**
> print text=[result](`second`)
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.
**> foreign.session_set id=`session` name="rate" value=0.08**
**rate = > foreign.session_get id=`session` name="rate"**
> print text=`rate`
**> 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.
---
Notebook sessions.
A document can declare named kernels and a cell order without new Markdown markers:
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | shared analysis |
| 复核 | python | | isolated review |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | write state |
| 计算指标 | 分析 | read state |
| 独立复核 | 复核 | isolated kernel |
```
Live `view` then adds Run All, Step, kernel switching, a journal and per-cell state. See the complete Python walkthrough in [`features/19-foreign-notebook.mq.md`](../features/19-foreign-notebook.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 | file sandbox root; no implicit escape |
| 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).
+134 -9
View File
@@ -1,20 +1,145 @@
---
title: lib/外联 — 外部语言
description: 从 Marqdo 调用本机解释器(中文)
title: lib/外联 — 外联内核 v2
description: 结构化执行、JSON 调用、并行扇出、持久内核与显式状态桥
导入 外联:lib/外联.mq.md
---
# main
导入 lib/外联.mq.md。代码围栏与公式同构:空 RHS 赋值后跟 lang 代码块,得到 code 类型。用 运行 代码=`名` 调用本机解释器。
`lib/外联` 用本机解释器运行代码围栏和内联源码。v2 不改 Markdown 表面,新增结构化记录、JSON 进出、并行扇出、Python/Node 持久内核和显式状态桥。
`hi` =
```python
print("hello-from-python")
文件仍然是一篇文档:绑定的代码围栏是可读的 Markdown,`外联.*` 把它变成可执行单元。
---
先探测,再运行。
**node = > 外联.探测 语言="node"**
> 打印 内容=[ok](`node`)
> 打印 内容=[version](`node`)
`探测` 返回 `{lang, cmd, path, ok, version, error}`。省略语言时探测所有已知语言。
---
结构化记录,而不只是 stdout。
`标记` =
```node
console.log("来自外联内核的问候");
```
默认命令可用 设置命令 或 MARQDO_FOREIGN_PYTHON 覆盖;live view 里可改命令框再点 Run。
**记录 = > 外联.执行 代码=`标记`**
**`out` = [外联.运行] 代码=`hi`**
> 打印 内容=[ok](`记录`)
> 打印 内容=[stdout](`记录`)
> 打印 内容=[code](`记录`)
> print text=`out`
`执行` 在进程失败时不抛错,而是在一条记录里给出 `ok`、`code`、`stdout`、`stderr`、`ms`、`timed_out`、`truncated`、`result` 与 `error`。
---
JSON 进,JSON 出。
`双倍` =
```node
let input = "";
process.stdin.on("data", chunk => { input += chunk; });
process.stdin.on("end", () => {
console.log(JSON.stringify(JSON.parse(input) * 2));
});
```
**单个 = > 外联.调用 代码=`双倍` 输入=21**
> 打印 内容=`单个`
输入编码成 JSON 写到 stdin;stdout 的最后一个值再解析成 JSON。想同时保留原始记录时,用 `执行` 的 `输出="json"`。
---
并行扇出。
`数值表` =
| 数值 |
|------|
| 1 |
| 2 |
| 3 |
| 4 |
**翻倍 = > 外联.批量调用 代码=`双倍` 输入表=`数值表` 并发=4**
> 打印 内容=`翻倍`
`批量调用` 对每个输入独立运行同一程序,保持输入顺序并返回解析后的 JSON 列表;`批量运行` 对完整 invoke 选项表做同样的事。
---
持久内核。
**会话 = > 外联.会话开启 语言="node"**
**第一次 = > 外联.会话求值 标识=`会话` 源码="let total = 0; for (let i = 1; i <= 5; i += 1) total += i;"**
**第二次 = > 外联.会话求值 标识=`会话` 源码="total * 2"**
> 打印 内容=[result](`第二次`)
第一次求值创建的变量会保留到第二次。内核不是 shell:用 `会话求值`、`会话取值`、`会话变量`,最后 `会话关闭`。
---
显式状态桥。
**> 外联.会话设值 标识=`会话` 名称="rate" 值=0.08**
**利率 = > 外联.会话取值 标识=`会话` 名称="rate"**
> 打印 内容=`利率`
**> 外联.会话关闭 标识=`会话`**
这是 JSON 拷贝,不是共享内存:内核收到一个值,Marqdo 取回一个值。没有隐式镜像,也没有隐藏的全局命名空间。
---
Notebook 会话。
文档可以直接声明命名内核和单元顺序,不需要新增 Markdown 标记:
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | 共享分析 |
| 复核 | python | | 独立复核 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | 写入状态 |
| 计算指标 | 分析 | 读取状态 |
| 独立复核 | 复核 | 隔离内核 |
```
live `view` 会提供 Run All、Step、切换内核、journal 和单元状态。完整 Python 示例见 [`features/19-外联Notebook.mq.md`](../features/19-外联Notebook.mq.md)。
---
安全默认值。
| 边界 | 默认 |
|---|---|
| 执行 | 需要宿主执行能力 |
| Shell | 不经过 shell;参数显式切分 |
| 输出 | 有界,带 truncated |
| 超时 | Unix 杀进程组 / Windows taskkill /T |
| 工作目录 | 文件沙箱根目录;不隐式越界 |
| 并行 | 扇出有上限;每个任务隔离 |
完整 API 见 [../../lib/外联.mq.md](../../lib/外联.mq.md),设计见 [../../doc/design/foreign-kernel.md](../../doc/design/foreign-kernel.md)。
+26
View File
@@ -39,6 +39,32 @@ run tests/ext/agent-zero-llm.mq.md
run tests/ext/agent-plan-preserve.mq.md
run examples/agent-okf-flywheel/index.mq.md
run examples/agent-pong/index.mq.md
run examples/agent-sandbox-okf/index.mq.md
run tests/ext/agent-sandbox-optin.mq.md
run tests/ext/agent-sandbox-promote.mq.md
# Skill Lift subset (O2 B3/E1): with-skill vs without — constitution / writeback / call_site markers.
skill_lift_pass=0
skill_lift_fail=0
assert_out_has() {
local f="$1"
local needle="$2"
local label="$3"
local out
out="$("$MQ" run "$f" 2>/dev/null || true)"
if printf '%s' "$out" | grep -q -- "$needle"; then
echo "SkillLift OK $label ($needle)"
skill_lift_pass=$((skill_lift_pass + 1))
else
echo "SkillLift MISS $label (need $needle)" >&2
skill_lift_fail=$((skill_lift_fail + 1))
fail=1
fi
}
assert_out_has tests/ext/agent-constitution-b0.mq.md "constitution-ok" "constitution"
assert_out_has tests/ext/agent-writeback-shadow.mq.md "writeback-shadow-ok" "writeback"
assert_out_has tests/ext/agent-dump-context.mq.md "dump-context-ok" "call_site"
echo "SkillLift summary: pass=$skill_lift_pass fail=$skill_lift_fail"
if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
export AGENT_LIVE=1
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# O4 — style gate: flag json.set dict chains and mixed EN/ZH API hints in .mq.md.
# Exit 0 when clean; 1 when findings (unless MQ_STYLE_LINT_SOFT=1).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
TARGETS=("$@")
if [[ ${#TARGETS[@]} -eq 0 ]]; then
TARGETS=(ext/ai/sandbox.mq.md ext/ai/policies examples/agent-sandbox-okf)
fi
fail=0
findings=0
scan_file() {
local f="$1"
[[ -f "$f" ]] || return 0
# Long json.set pipelines (3+ consecutive) — style bug per marqdo-dev.
if awk '
/json\.set/ { c++; if (c >= 3) { found=1 } next }
{ c=0 }
END { exit found ? 0 : 1 }
' "$f"; then
echo "STYLE json.set-chain: $f" >&2
findings=$((findings + 1))
fail=1
fi
# Same file imports both EN agent and ZH 智能体 (or web/网页) — mixed surface.
if grep -qE 'import[[:space:]]+agent:|import[[:space:]]+web:' "$f" \
&& grep -qE '导入[[:space:]]+(智能体|网页):' "$f"; then
echo "STYLE mixed-EN/ZH-import: $f" >&2
findings=$((findings + 1))
fail=1
fi
}
while IFS= read -r -d '' f; do
scan_file "$f"
done < <(find "${TARGETS[@]}" -type f -name '*.mq.md' -print0 2>/dev/null)
echo "mq-style-lint: findings=$findings"
if [[ "${MQ_STYLE_LINT_SOFT:-}" == "1" ]]; then
exit 0
fi
exit "$fail"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# O5 — offline standing / policy rewrite hint (GEPA-like, products stay repo files).
# Does NOT change the runtime agent path. Reads harness failure log + current files,
# writes a suggested patch under .marqdo/optimize/ for human review.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
LOG="${1:-}"
STANDING="${2:-ext/ai/agent.mq.md}"
POLICY="${3:-ext/ai/policies/step-route.mq.md}"
OUT_DIR="${OUT_DIR:-.marqdo/optimize}"
mkdir -p "$OUT_DIR"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
REPORT="$OUT_DIR/standing-policy-$STAMP.md"
{
echo "# Offline standing / policy optimize suggestion"
echo
echo "Generated: $STAMP"
echo
echo "This is a **review artifact**, not an automatic runtime rewrite."
echo "Strong models may rewrite \`standing\` / \`policies/*.mq.md\` offline;"
echo "commit only after harness green."
echo
echo "## Inputs"
echo
echo "- standing source: \`$STANDING\`"
echo "- policy source: \`$POLICY\`"
if [[ -n "$LOG" && -f "$LOG" ]]; then
echo "- harness log: \`$LOG\`"
echo
echo "## Harness failure excerpt"
echo
echo '```'
tail -n 80 "$LOG" || true
echo '```'
else
echo "- harness log: _(none — pass path as \$1)_"
fi
echo
echo "## Current policy table (copy)"
echo
if [[ -f "$POLICY" ]]; then
echo '```markdown'
cat "$POLICY"
echo '```'
else
echo "_missing $POLICY_"
fi
echo
echo "## Suggested next edits"
echo
echo "1. Keep step-class → backend as a **GFM table** (no json glue)."
echo "2. Quarantine failing skills (\`status: quarantine\`) before promoting again."
echo "3. Re-run \`scripts/agent-harness.sh\` and confirm Skill Lift summary."
} > "$REPORT"
echo "wrote $REPORT"
+4 -1
View File
@@ -124,7 +124,10 @@ if [ "$REUSE_ORIG" -eq 1 ]; then
echo "==> reusing published ${ORIG_NAME} (debian-only bump; do not rewrite orig)"
echo " source: ${ORIG_SRC}"
sha256sum "$ORIG_SRC"
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
# Local fallback may already be build-area/ORIG_NAME — do not cp onto itself.
if [ "$(realpath "$ORIG_SRC")" != "$(realpath "$BUILD_AREA/$ORIG_NAME" 2>/dev/null || echo "")" ]; then
cp -f "$ORIG_SRC" "$BUILD_AREA/$ORIG_NAME"
fi
# Unpack orig (top dir is usually ${VER} or marqdo-${VER})
tar -xJf "$BUILD_AREA/$ORIG_NAME" -C "$(dirname "$PKG_ROOT")"
if [ ! -d "$PKG_ROOT" ]; then
+6 -2
View File
@@ -32,7 +32,9 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## Markup → meaning (v0.2)
@@ -162,7 +164,9 @@ Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --releas
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
+61 -5
View File
@@ -124,11 +124,67 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
("host_json_stringify" | "stringify", "indent" | "缩进") => "indent".into(),
("host_plot", "steps" | "步数") => "steps".into(),
("host_plot", "derivative" | "导数") => "derivative".into(),
("host_foreign_run", "code" | "代码") => "code".into(),
("host_foreign_run" | "host_foreign_run_lang", "stdin" | "标准输入") => "stdin".into(),
("host_foreign_set_cmd" | "host_foreign_run_lang", "lang" | "语言") => "lang".into(),
("host_foreign_set_cmd", "cmd" | "命令") => "cmd".into(),
("host_foreign_run_lang", "source" | "源码") => "source".into(),
("host_foreign_run" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_eval", "code" | "代码") => "code".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke"
| "host_foreign_call",
"stdin" | "标准输入",
) => "stdin".into(),
(
"host_foreign_set_cmd"
| "host_foreign_run_lang"
| "host_foreign_invoke"
| "host_foreign_probe"
| "host_foreign_register"
| "host_foreign_unset"
| "host_foreign_call"
| "host_foreign_call_many"
| "host_foreign_session_open",
"lang" | "语言",
) => "lang".into(),
(
"host_foreign_set_cmd"
| "host_foreign_invoke"
| "host_foreign_register"
| "host_foreign_call_many"
| "host_foreign_session_open",
"cmd" | "命令",
) => "cmd".into(),
("host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_eval", "source" | "源码") => "source".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval",
"env" | "环境",
) => "env".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval",
"cwd" | "工作目录",
) => "cwd".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call" | "host_foreign_call_many" | "host_foreign_session_open" | "host_foreign_session_eval",
"timeout" | "超时",
) => "timeout".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke"
| "host_foreign_register" | "host_foreign_call" | "host_foreign_call_many",
"args" | "参数",
) => "args".into(),
(
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke" | "host_foreign_call_many",
"max_output" | "最大输出",
) => "max_output".into(),
("host_foreign_invoke" | "host_foreign_call" | "host_foreign_session_eval", "input" | "输入") => "input".into(),
("host_foreign_session_eval" | "host_foreign_session_set" | "host_foreign_session_get" | "host_foreign_session_names" | "host_foreign_session_close", "id" | "标识") => "id".into(),
("host_foreign_session_set" | "host_foreign_session_get", "name" | "名称") => "name".into(),
("host_foreign_session_set", "value" | "值") => "value".into(),
("host_foreign_invoke", "output" | "输出") => "output".into(),
("host_foreign_invoke", "keep" | "保留") => "keep".into(),
("host_foreign_register", "template" | "模板") => "template".into(),
("host_foreign_register", "ext" | "扩展名") => "ext".into(),
("host_foreign_register", "version_args" | "版本参数") => "version_args".into(),
("host_foreign_load_config", "path" | "路径") => "path".into(),
("host_foreign_run_many", "runs" | "任务表") => "runs".into(),
("host_foreign_call_many", "inputs" | "输入表") => "inputs".into(),
("host_foreign_run_many" | "host_foreign_call_many", "concurrency" | "并发") => "concurrency".into(),
("host_ext_native_path", "name" | "名") => "name".into(),
_ => param.to_string(),
}
+94 -1
View File
@@ -1,7 +1,98 @@
//! Captured program run (for tests and `view`).
use crate::value::Value;
use crate::host::PlotArtifact;
use crate::value::Value;
/// Silent execution trace for view annotations (not stderr `trace_eval`).
#[derive(Debug, Clone, Default)]
pub struct ViewTrace {
pub branches: Vec<BranchHit>,
pub loops: Vec<LoopHit>,
/// Per-statement post-state / control events (tree capture).
pub events: Vec<StmtEvent>,
/// User-function invocations (tree capture).
pub calls: Vec<CallFrame>,
/// Foreach / while loop frames with per-iteration item values.
pub loop_frames: Vec<LoopFrame>,
}
#[derive(Debug, Clone)]
pub struct BranchHit {
pub line: u32,
pub arm_index: usize,
pub count: u32,
/// Call frame that took this arm (`0` = entry / `# main`).
pub call_id: u32,
}
#[derive(Debug, Clone)]
pub struct LoopHit {
pub line: u32,
pub iterations: u32,
pub last_item: Option<String>,
}
#[derive(Debug, Clone)]
pub struct LoopFrame {
pub loop_id: u32,
pub line: u32,
pub item_name: Option<String>,
pub collection: Option<String>,
pub iterations: Vec<LoopIter>,
}
#[derive(Debug, Clone)]
pub struct LoopIter {
/// 0-based iteration index.
pub index: u32,
pub item_value: String,
pub call_id: u32,
}
#[derive(Debug, Clone)]
pub struct StmtEvent {
pub line: u32,
pub kind: StmtEventKind,
pub name: Option<String>,
pub value_after: Option<String>,
pub arm_index: Option<usize>,
/// 0-based iteration index when inside a loop.
pub iter: Option<u32>,
pub call_id: u32,
pub loop_id: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StmtEventKind {
Assign,
Return,
Call,
Branch,
Loop,
BindRef,
}
impl StmtEventKind {
pub fn as_str(self) -> &'static str {
match self {
StmtEventKind::Assign => "assign",
StmtEventKind::Return => "return",
StmtEventKind::Call => "call",
StmtEventKind::Branch => "branch",
StmtEventKind::Loop => "loop",
StmtEventKind::BindRef => "bind_ref",
}
}
}
#[derive(Debug, Clone)]
pub struct CallFrame {
pub call_id: u32,
pub fn_name: String,
pub fn_line: u32,
pub ordinal: u32,
pub args_brief: String,
}
#[derive(Debug, Clone)]
pub struct RunCapture {
@@ -10,4 +101,6 @@ pub struct RunCapture {
pub plots: Vec<PlotArtifact>,
/// Entry-function bindings after a successful tree-backend run (empty for bytecode).
pub bindings: std::collections::HashMap<String, Value>,
/// Branch/loop/stmt hits collected during tree capture (empty for bytecode).
pub view_trace: ViewTrace,
}
+42 -23
View File
@@ -1,30 +1,49 @@
//! Foreign / code-block helpers (外联).
/// Default interpreter argv for a language tag (before env / set_cmd).
pub fn default_argv(lang: &str) -> Option<Vec<String>> {
match lang.to_ascii_lowercase().as_str() {
"python" | "python3" | "py" => Some(default_python_argv()),
"javascript" | "js" | "node" => Some(vec!["node".into()]),
_ => None,
}
}
pub mod registry;
pub fn default_python_argv() -> Vec<String> {
#[cfg(windows)]
{
vec!["python".into()]
}
#[cfg(not(windows))]
{
vec!["python3".into()]
}
}
pub use registry::{default_argv, default_cmd_display, default_python_argv};
/// Placeholder shown in the view command box.
pub fn default_cmd_display(lang: &str) -> String {
default_argv(lang)
.map(|a| a.join(" "))
.unwrap_or_else(|| lang.to_string())
/// Shell-like split: whitespace, single/double quotes, backslash escapes.
pub fn split_cmd_line(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut quote: Option<char> = None;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match quote {
Some(q) => {
if c == q {
quote = None;
} else if c == '\\' && q == '"' {
if let Some(n) = chars.next() {
cur.push(n);
}
} else {
cur.push(c);
}
}
None => {
if c.is_whitespace() {
if !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
} else if c == '\'' || c == '"' {
quote = Some(c);
} else if c == '\\' {
if let Some(n) = chars.next() {
cur.push(n);
}
} else {
cur.push(c);
}
}
}
}
if !cur.is_empty() {
out.push(cur);
}
out
}
/// Parse ```lang … opener → language id (first token).
+188
View File
@@ -0,0 +1,188 @@
//! Language presets and specs for `lib/foreign` (pure data; no process spawning).
//!
//! The host runner resolves a `LangSpec`, then builds the command. Keeping this
//! module free of `std::process` lets the browser/wasm build share the syntax and
//! preset tables.
use std::path::PathBuf;
/// One language's invocation recipe.
#[derive(Debug, Clone, Default)]
pub struct LangSpec {
pub lang: String,
/// Simple interpreter prefix; the script path is appended.
pub argv: Vec<String>,
/// Optional full argv template; supports `{file}`/`{inline}`/… placeholders.
pub template: Option<Vec<String>>,
pub ext: Option<String>,
pub env: Vec<(String, String)>,
/// Arguments appended to the executable for `probe` (e.g. `--version`).
pub version_args: Vec<String>,
/// Persistent session bootstrap available.
pub session: bool,
/// Directory for resolving a relative interpreter path (config file dir).
pub base_dir: Option<PathBuf>,
}
impl LangSpec {
fn simple(lang: &str, argv: &[&str], ext: &str, version: &[&str], session: bool) -> Self {
Self {
lang: lang.to_string(),
argv: argv.iter().map(|s| (*s).to_string()).collect(),
template: None,
ext: Some(ext.to_string()),
env: Vec::new(),
version_args: version.iter().map(|s| (*s).to_string()).collect(),
session,
base_dir: None,
}
}
fn templated(lang: &str, template: &[&str], ext: &str, version: &[&str]) -> Self {
Self {
lang: lang.to_string(),
argv: vec![template[0].to_string()],
template: Some(template.iter().map(|s| (*s).to_string()).collect()),
ext: Some(ext.to_string()),
env: Vec::new(),
version_args: version.iter().map(|s| (*s).to_string()).collect(),
session: false,
base_dir: None,
}
}
}
pub fn default_python_argv() -> Vec<String> {
#[cfg(windows)]
{
vec!["python".into()]
}
#[cfg(not(windows))]
{
vec!["python3".into()]
}
}
/// Canonical preset id for a language or alias. Unknown names pass through lowercased.
pub fn canonical(lang: &str) -> String {
let l = lang.to_ascii_lowercase();
match l.as_str() {
"python3" | "py" => "python".into(),
"javascript" | "js" => "node".into(),
"shell" | "sh" => "bash".into(),
"rscript" => "r".into(),
"pwsh" | "ps1" => "powershell".into(),
"sqlite3" => "sqlite".into(),
"typescript" => "tsx".into(),
_ => l,
}
}
/// Built-in preset for a language/alias.
pub fn preset_spec(lang: &str) -> Option<LangSpec> {
let id = canonical(lang);
Some(match id.as_str() {
"python" => LangSpec {
argv: default_python_argv(),
..LangSpec::simple("python", &["python3"], "py", &["--version"], true)
},
"node" => LangSpec::simple("node", &["node"], "js", &["-v"], true),
"deno" => LangSpec::simple("deno", &["deno", "run"], "ts", &["--version"], false),
"bun" => LangSpec::simple("bun", &["bun"], "js", &["--version"], false),
"ruby" => LangSpec::simple("ruby", &["ruby"], "rb", &["--version"], false),
"perl" => LangSpec::simple("perl", &["perl"], "pl", &["--version"], false),
"php" => LangSpec::templated("php", &["php", "-r", "{inline}"], "php", &["--version"]),
"lua" => LangSpec::simple("lua", &["lua"], "lua", &["-v"], false),
"r" => LangSpec::simple("r", &["Rscript"], "R", &["--version"], false),
"julia" => LangSpec::simple("julia", &["julia"], "jl", &["--version"], false),
"go" => LangSpec::templated("go", &["go", "run", "{file}"], "go", &["version"]),
"bash" => LangSpec::simple("bash", &["bash"], "sh", &["--version"], false),
"powershell" => {
#[cfg(windows)]
{
LangSpec::simple("powershell", &["powershell"], "ps1", &["--version"], false)
}
#[cfg(not(windows))]
{
LangSpec::simple("powershell", &["pwsh"], "ps1", &["--version"], false)
}
}
"sqlite" => LangSpec::simple("sqlite", &["sqlite3"], "sql", &["--version"], false),
"tsx" => LangSpec::simple("tsx", &["tsx"], "ts", &["--version"], false),
_ => return None,
})
}
/// Sorted preset ids (for `langs`).
pub fn preset_ids() -> Vec<String> {
[
"python", "node", "deno", "bun", "ruby", "perl", "php", "lua", "r", "julia", "go",
"bash", "powershell", "sqlite", "tsx",
]
.iter()
.map(|s| (*s).to_string())
.collect()
}
/// Display string for the command box (e.g. `python3`, `go run`, `php -r`).
pub fn default_cmd_display(lang: &str) -> String {
match preset_spec(lang) {
Some(spec) => {
if let Some(t) = &spec.template {
let mut parts = Vec::new();
for x in t {
if x.contains('{') {
break;
}
parts.push(x.clone());
}
if parts.is_empty() {
lang.to_string()
} else {
parts.join(" ")
}
} else {
spec.argv.join(" ")
}
}
None => lang.to_string(),
}
}
/// Default argv for v1 compatibility (simple presets only).
pub fn default_argv(lang: &str) -> Option<Vec<String>> {
preset_spec(lang).map(|s| s.argv)
}
/// Session support for a language (based on preset).
pub fn session_supported(lang: &str) -> bool {
preset_spec(lang).map(|s| s.session).unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aliases_canonicalize() {
assert_eq!(canonical("py"), "python");
assert_eq!(canonical("javascript"), "node");
assert_eq!(canonical("sh"), "bash");
assert_eq!(canonical("unknown"), "unknown");
}
#[test]
fn presets_cover_docs() {
assert_eq!(preset_ids().len(), 15);
assert!(preset_spec("python").is_some());
assert!(preset_spec("node").is_some());
assert!(preset_spec("go").unwrap().template.is_some());
assert!(preset_spec("php").unwrap().template.is_some());
}
#[test]
fn display_uses_template_prefix() {
assert_eq!(default_cmd_display("go"), "go run");
assert_eq!(default_cmd_display("php"), "php -r");
}
}
+386 -3
View File
@@ -202,6 +202,21 @@ pub enum HostFn {
MetaGet = 193,
ModuleSource = 194,
ArtifactKind = 195,
ForeignInvoke = 196,
ForeignProbe = 197,
ForeignRegister = 198,
ForeignUnset = 199,
ForeignLoadConfig = 200,
ForeignCall = 201,
ForeignRunMany = 202,
ForeignCallMany = 203,
ForeignSessionOpen = 204,
ForeignSessionEval = 205,
ForeignSessionSet = 206,
ForeignSessionGet = 207,
ForeignSessionNames = 208,
ForeignSessionClose = 209,
ForeignSessionList = 210,
}
@@ -394,6 +409,21 @@ impl HostFn {
193 => Self::MetaGet,
194 => Self::ModuleSource,
195 => Self::ArtifactKind,
196 => Self::ForeignInvoke,
197 => Self::ForeignProbe,
198 => Self::ForeignRegister,
199 => Self::ForeignUnset,
200 => Self::ForeignLoadConfig,
201 => Self::ForeignCall,
202 => Self::ForeignRunMany,
203 => Self::ForeignCallMany,
204 => Self::ForeignSessionOpen,
205 => Self::ForeignSessionEval,
206 => Self::ForeignSessionSet,
207 => Self::ForeignSessionGet,
208 => Self::ForeignSessionNames,
209 => Self::ForeignSessionClose,
210 => Self::ForeignSessionList,
_ => return None,
})
}
@@ -470,6 +500,21 @@ impl HostFn {
"host_foreign_set_cmd" => Self::ForeignSetCmd,
"host_foreign_run" => Self::ForeignRun,
"host_foreign_run_lang" => Self::ForeignRunLang,
"host_foreign_invoke" | "foreign_invoke" => Self::ForeignInvoke,
"host_foreign_probe" | "foreign_probe" => Self::ForeignProbe,
"host_foreign_register" | "foreign_register" => Self::ForeignRegister,
"host_foreign_unset" | "foreign_unset" => Self::ForeignUnset,
"host_foreign_load_config" | "foreign_load_config" => Self::ForeignLoadConfig,
"host_foreign_call" | "foreign_call" => Self::ForeignCall,
"host_foreign_run_many" | "foreign_run_many" => Self::ForeignRunMany,
"host_foreign_call_many" | "foreign_call_many" => Self::ForeignCallMany,
"host_foreign_session_open" | "foreign_session_open" => Self::ForeignSessionOpen,
"host_foreign_session_eval" | "foreign_session_eval" => Self::ForeignSessionEval,
"host_foreign_session_set" | "foreign_session_set" => Self::ForeignSessionSet,
"host_foreign_session_get" | "foreign_session_get" => Self::ForeignSessionGet,
"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_langs" => Self::ForeignLangs,
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
"host_http_request" | "http_request" => Self::HttpRequest,
@@ -666,6 +711,21 @@ impl HostFn {
Self::ForeignSetCmd => "host_foreign_set_cmd",
Self::ForeignRun => "host_foreign_run",
Self::ForeignRunLang => "host_foreign_run_lang",
Self::ForeignInvoke => "host_foreign_invoke",
Self::ForeignProbe => "host_foreign_probe",
Self::ForeignRegister => "host_foreign_register",
Self::ForeignUnset => "host_foreign_unset",
Self::ForeignLoadConfig => "host_foreign_load_config",
Self::ForeignCall => "host_foreign_call",
Self::ForeignRunMany => "host_foreign_run_many",
Self::ForeignCallMany => "host_foreign_call_many",
Self::ForeignSessionOpen => "host_foreign_session_open",
Self::ForeignSessionEval => "host_foreign_session_eval",
Self::ForeignSessionSet => "host_foreign_session_set",
Self::ForeignSessionGet => "host_foreign_session_get",
Self::ForeignSessionNames => "host_foreign_session_names",
Self::ForeignSessionClose => "host_foreign_session_close",
Self::ForeignSessionList => "host_foreign_session_list",
Self::ForeignLangs => "host_foreign_langs",
Self::DotenvLoad => "host_dotenv_load",
Self::HttpRequest => "host_http_request",
@@ -832,6 +892,18 @@ impl HostFn {
Self::ForeignSetCmd => &["lang", "cmd"],
Self::ForeignRun => &["code"],
Self::ForeignRunLang => &["lang", "source"],
Self::ForeignInvoke | Self::ForeignCall => &[],
Self::ForeignProbe | Self::ForeignLoadConfig => &[],
Self::ForeignRegister | Self::ForeignUnset => &["lang"],
Self::ForeignRunMany => &["runs"],
Self::ForeignCallMany => &["inputs"],
Self::ForeignSessionOpen => &["lang"],
Self::ForeignSessionEval => &["id"],
Self::ForeignSessionSet => &["id", "name", "value"],
Self::ForeignSessionGet => &["id", "name"],
Self::ForeignSessionNames => &["id"],
Self::ForeignSessionClose => &["id"],
Self::ForeignSessionList => &[],
Self::ForeignLangs => &[],
Self::PluginLoad => &["path"],
Self::PluginUnload | Self::PluginList => &[],
@@ -935,7 +1007,58 @@ impl HostFn {
Self::PlotPoints => &["path", "grid"],
Self::PlotConic => &["b", "h", "k", "path", "grid"],
Self::ForeignSetCmd => &["args"],
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
Self::ForeignRun | Self::ForeignRunLang => {
&["stdin", "env", "cwd", "timeout", "args", "max_output"]
}
Self::ForeignInvoke => &[
"code",
"lang",
"source",
"stdin",
"input",
"env",
"cwd",
"timeout",
"args",
"output",
"max_output",
"cmd",
"keep",
],
Self::ForeignProbe => &["lang"],
Self::ForeignRegister => &[
"cmd",
"args",
"template",
"ext",
"env",
"version_args",
],
Self::ForeignUnset => &[],
Self::ForeignLoadConfig => &["path"],
Self::ForeignCall => &[
"code", "lang", "source", "input", "stdin", "env", "cwd", "timeout", "args",
],
Self::ForeignRunMany => &["concurrency"],
Self::ForeignCallMany => &[
"code",
"lang",
"source",
"cmd",
"env",
"cwd",
"timeout",
"args",
"max_output",
"concurrency",
],
Self::ForeignSessionOpen => &["cmd", "env", "cwd", "timeout"],
Self::ForeignSessionEval => &["code", "source", "input", "timeout"],
Self::ForeignSessionSet
| Self::ForeignSessionGet
| Self::ForeignSessionNames
| Self::ForeignSessionClose
| Self::ForeignSessionList => &[],
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => {
&["at_end", "key", "line"]
}
@@ -1184,7 +1307,12 @@ pub fn call_host(
HostFn::ForeignRun => {
#[cfg(feature = "exec-host")]
{
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
foreign::run_with_options(
ctx,
require(bound, "code")?,
bound.get("stdin"),
bound,
)
}
#[cfg(not(feature = "exec-host"))]
{
@@ -1195,11 +1323,12 @@ pub fn call_host(
HostFn::ForeignRunLang => {
#[cfg(feature = "exec-host")]
{
foreign::run_lang(
foreign::run_lang_with_options(
ctx,
require(bound, "lang")?,
require(bound, "source")?,
bound.get("stdin"),
bound,
)
}
#[cfg(not(feature = "exec-host"))]
@@ -1208,6 +1337,260 @@ pub fn call_host(
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignInvoke => {
#[cfg(feature = "exec-host")]
{
foreign::invoke(
ctx,
foreign::InvokeArgs {
code: bound.get("code"),
lang: bound.get("lang"),
source: bound.get("source"),
stdin: bound.get("stdin"),
input: bound.get("input"),
env: bound.get("env"),
cwd: bound.get("cwd"),
timeout: bound.get("timeout"),
args: bound.get("args"),
output: bound.get("output"),
max_output: bound.get("max_output"),
cmd: bound.get("cmd"),
keep: bound.get("keep"),
},
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignProbe => {
#[cfg(feature = "exec-host")]
{
foreign::probe(ctx, bound.get("lang"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRegister => {
#[cfg(feature = "exec-host")]
{
foreign::register(
ctx,
require(bound, "lang")?,
bound.get("cmd"),
bound.get("args"),
bound.get("template"),
bound.get("ext"),
bound.get("env"),
bound.get("version_args"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignUnset => {
#[cfg(feature = "exec-host")]
{
foreign::unset(ctx, require(bound, "lang")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignLoadConfig => {
#[cfg(feature = "exec-host")]
{
foreign::load_config(ctx, bound.get("path"))
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignCall => {
#[cfg(feature = "exec-host")]
{
foreign::call(
ctx,
foreign::InvokeArgs {
code: bound.get("code"),
lang: bound.get("lang"),
source: bound.get("source"),
stdin: bound.get("stdin"),
input: bound.get("input"),
env: bound.get("env"),
cwd: bound.get("cwd"),
timeout: bound.get("timeout"),
args: bound.get("args"),
output: None,
max_output: None,
cmd: None,
keep: None,
},
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignRunMany => {
#[cfg(feature = "exec-host")]
{
foreign::run_many(
ctx,
require(bound, "runs")?,
bound.get("concurrency"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignCallMany => {
#[cfg(feature = "exec-host")]
{
foreign::call_many(
ctx,
foreign::InvokeArgs {
code: bound.get("code"),
lang: bound.get("lang"),
source: bound.get("source"),
stdin: None,
input: None,
env: bound.get("env"),
cwd: bound.get("cwd"),
timeout: bound.get("timeout"),
args: bound.get("args"),
output: None,
max_output: bound.get("max_output"),
cmd: bound.get("cmd"),
keep: None,
},
require(bound, "inputs")?,
bound.get("concurrency"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionOpen => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::open(
ctx,
require(bound, "lang")?,
bound.get("cmd"),
bound.get("env"),
bound.get("cwd"),
bound.get("timeout"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionEval => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::eval(
ctx,
require(bound, "id")?,
bound.get("code"),
bound.get("source"),
bound.get("input"),
bound.get("timeout"),
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionSet => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::set(
ctx,
require(bound, "id")?,
require(bound, "name")?,
require(bound, "value")?,
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionGet => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::get(
ctx,
require(bound, "id")?,
require(bound, "name")?,
)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionNames => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::names(ctx, require(bound, "id")?)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, bound);
Err("foreign unavailable in browser wasm".into())
}
}
HostFn::ForeignSessionClose => {
#[cfg(feature = "exec-host")]
{
crate::host::foreign_session::close(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")]
{
crate::host::foreign_session::list(ctx)
}
#[cfg(not(feature = "exec-host"))]
{
let _ = ctx;
Ok(Value::List(Vec::new()))
}
}
HostFn::ForeignLangs => {
#[cfg(feature = "exec-host")]
{
+1814 -225
View File
File diff suppressed because it is too large. Load diff
+737
View File
@@ -0,0 +1,737 @@
//! Persistent foreign kernels (Python / Node) and the session state bridge.
//!
//! Protocol: one JSON request per stdin line, one JSON response per original
//! stdout line. User stdout/stderr are captured inside the bootstrap.
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::host::foreign::{ensure_config, resolve_session_spec};
use crate::host::json::{json_to_value, value_to_json};
use crate::host::HostContext;
use crate::value::Value;
const SESSION_TIMEOUT_SECS: f64 = 10.0;
const MAX_SESSION_TIMEOUT_SECS: f64 = 3600.0;
const MAX_PROCESS_STDERR: usize = 1_048_576;
const PY_BOOTSTRAP: &str = r#"import sys, json, io, ast, traceback, contextlib
_out = sys.stdout
def _send(o):
_out.write(json.dumps(o, ensure_ascii=False, default=str) + "\n")
_out.flush()
_g = {"__name__": "__main__", "marqdo_input": None}
for _line in sys.stdin:
_line = _line.strip()
if not _line:
continue
try:
req = json.loads(_line)
except Exception:
_send({"id": None, "ok": False, "stdout": "", "stderr": "", "result": None, "error": "bad request"})
continue
rid = req.get("id")
op = req.get("op", "eval")
if op == "set":
_g[req.get("name")] = req.get("value")
_send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": None, "error": ""})
continue
if op == "get":
try:
_val = _g[req.get("name")]
except KeyError:
_val = None
_send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": _val, "error": ""})
continue
if op == "names":
_names = sorted(k for k in _g.keys() if not k.startswith("__"))
_send({"id": rid, "ok": True, "stdout": "", "stderr": "", "result": _names, "error": ""})
continue
_code = req.get("code", "")
_g["marqdo_input"] = req.get("input")
_out_buf = io.StringIO()
_err_buf = io.StringIO()
try:
_tree = ast.parse(_code, "<marqdo>")
_result = None
with contextlib.redirect_stdout(_out_buf), contextlib.redirect_stderr(_err_buf):
if _tree.body and isinstance(_tree.body[-1], ast.Expr):
_last = _tree.body.pop()
if _tree.body:
exec(compile(_tree, "<marqdo>", "exec"), _g)
_result = eval(compile(ast.Expression(_last.value), "<marqdo>", "eval"), _g)
else:
exec(compile(_tree, "<marqdo>", "exec"), _g)
_send({"id": rid, "ok": True, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": _result, "error": ""})
except BaseException:
_send({"id": rid, "ok": False, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": None, "error": traceback.format_exc(limit=8)})
"#;
const JS_BOOTSTRAP: &str = r#"const readline = require("readline");
const util = require("util");
const vm = require("vm");
const out = process.stdout.write.bind(process.stdout);
globalThis.require = require;
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
function send(o) { out(JSON.stringify(o) + "\n"); }
function toJSON(v) { try { return JSON.parse(JSON.stringify(v)); } catch (e) { return String(v); } }
async function capture(fn) {
const logs = [], errs = [];
const ow = process.stdout.write.bind(process.stdout);
const ew = process.stderr.write.bind(process.stderr);
const ol = console.log, oi = console.info, owr = console.warn, oe = console.error;
console.log = console.info = (...a) => { logs.push(util.format(...a) + "\n"); };
console.warn = console.error = (...a) => { errs.push(util.format(...a) + "\n"); };
process.stdout.write = (c) => { logs.push(String(c)); return true; };
process.stderr.write = (c) => { errs.push(String(c)); return true; };
let result, error = "";
try { result = await fn(); } catch (e) { error = (e && e.stack) || String(e); }
process.stdout.write = ow; process.stderr.write = ew;
console.log = ol; console.info = oi; console.warn = owr; console.error = oe;
return { logs: logs.join(""), errs: errs.join(""), result: result === undefined ? null : result, error };
}
rl.on("line", async (line) => {
let req;
try { req = JSON.parse(line); } catch (e) { send({ id: null, ok: false, stdout: "", stderr: "", result: null, error: "bad request" }); return; }
const rid = req.id, op = req.op || "eval";
if (op === "set") { globalThis[req.name] = req.value; send({ id: rid, ok: true, stdout: "", stderr: "", result: null, error: "" }); return; }
if (op === "get") {
let result = null;
try { result = vm.runInThisContext(String(req.name), { filename: "<marqdo-get>" }); }
catch (e) { result = globalThis[req.name] === undefined ? null : globalThis[req.name]; }
send({ id: rid, ok: true, stdout: "", stderr: "", result: toJSON(result), error: "" });
return;
}
if (op === "names") {
const skip = new Set(["global","globalThis","process","Buffer","console","require","module","exports","__dirname","__filename","performance","crypto","navigator","fetch","URL","URLSearchParams","TextEncoder","TextDecoder","setTimeout","clearTimeout","setInterval","clearInterval","queueMicrotask","structuredClone","atob","btoa","marqdo_input"]);
const names = Object.keys(globalThis).filter(k => !k.startsWith("__") && !skip.has(k) && typeof globalThis[k] !== "function");
send({ id: rid, ok: true, stdout: "", stderr: "", result: names, error: "" });
return;
}
globalThis.marqdo_input = req.input === undefined ? null : req.input;
const cap = await capture(async () => vm.runInThisContext(req.code || "", { filename: "<marqdo>" }));
send({ id: rid, ok: !cap.error, stdout: cap.logs, stderr: cap.errs, result: toJSON(cap.result), error: cap.error });
});
"#;
pub struct Session {
pub id: String,
pub lang: String,
pub cmd: String,
pub started_ms: i64,
pub timeout: Duration,
pub evals: u64,
pub alive: bool,
child: Child,
stdin: std::process::ChildStdin,
rx: Receiver<String>,
_reader: JoinHandle<()>,
stderr: Arc<Mutex<String>>,
_stderr_reader: JoinHandle<()>,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("id", &self.id)
.field("lang", &self.lang)
.field("evals", &self.evals)
.field("alive", &self.alive)
.finish()
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn as_text<'a>(v: &'a Value, what: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{what} must be text")),
}
}
fn opt_text(v: Option<&Value>) -> Result<Option<String>, String> {
match v {
None | Some(Value::None) => Ok(None),
Some(Value::Text(s)) => Ok(Some(s.clone())),
Some(Value::Secret(s)) => Ok(Some(s.clone())),
Some(_) => Err("value must be text".into()),
}
}
fn parse_timeout(v: Option<&Value>, default: f64) -> Result<Duration, String> {
let secs = match v {
None | Some(Value::None) => default,
Some(Value::Int(n)) => *n as f64,
Some(Value::Num(n)) => *n,
Some(_) => return Err("timeout must be a number of seconds".into()),
};
if !secs.is_finite() || secs <= 0.0 {
return Err("timeout must be > 0 seconds".into());
}
Ok(Duration::from_secs_f64(secs.min(MAX_SESSION_TIMEOUT_SECS)))
}
fn parse_env(v: Option<&Value>) -> Result<Vec<(String, String)>, String> {
match v {
None | Some(Value::None) => Ok(Vec::new()),
Some(Value::Map(entries)) => Ok(entries
.iter()
.map(|(k, v)| {
let val = match v {
Value::Secret(s) => s.clone(),
other => other.as_display(),
};
(k.clone(), val)
})
.collect()),
Some(_) => Err("env must be a map".into()),
}
}
fn record(
id: Option<&str>,
lang: &str,
cmd: &str,
ok: bool,
stdout: String,
stderr: String,
result: Value,
error: String,
ms: u64,
timed_out: bool,
alive: bool,
) -> Value {
let mut fields = vec![
("ok".into(), Value::Bool(ok)),
("code".into(), Value::Int(if ok { 0 } else { -1 })),
("stdout".into(), Value::Text(stdout)),
("stderr".into(), Value::Text(stderr)),
("ms".into(), Value::Int(ms as i64)),
("lang".into(), Value::Text(lang.to_string())),
("cmd".into(), Value::Text(cmd.to_string())),
("timed_out".into(), Value::Bool(timed_out)),
("truncated".into(), Value::Bool(false)),
("result".into(), result),
("result_error".into(), Value::Text(String::new())),
("error".into(), Value::Text(error)),
("script".into(), Value::Text(String::new())),
("cached".into(), Value::Bool(false)),
("alive".into(), Value::Bool(alive)),
];
if let Some(id) = id {
fields.push(("id".into(), Value::Text(id.to_string())));
}
Value::Map(fields)
}
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
}
pub fn open(
ctx: &mut HostContext,
lang: &Value,
cmd: Option<&Value>,
env: Option<&Value>,
cwd: Option<&Value>,
timeout: Option<&Value>,
) -> Result<Value, String> {
ensure_config(ctx);
if !ctx.allow_exec() {
return Err("foreign session denied by host policy".into());
}
let requested = as_text(lang, "lang")?.to_ascii_lowercase();
let canonical = crate::foreign::registry::canonical(&requested);
if !crate::foreign::registry::session_supported(&canonical) {
return Err(format!(
"lang=`{canonical}` has no session bootstrap; use run/invoke"
));
}
let spec = resolve_session_spec(ctx, &canonical)?;
let mut argv = match opt_text(cmd)? {
Some(c) => {
let argv = crate::foreign::split_cmd_line(&c);
if argv.is_empty() {
return Err("session cmd override is empty".into());
}
argv
}
None => spec.argv.clone(),
};
if argv.is_empty() {
return Err(format!("no interpreter configured for lang=`{canonical}`"));
}
match canonical.as_str() {
"python" => {
argv.push("-u".into());
argv.push("-c".into());
argv.push(PY_BOOTSTRAP.into());
}
"node" => {
argv.push("-e".into());
argv.push(JS_BOOTSTRAP.into());
}
_ => return Err(format!("lang=`{canonical}` has no session bootstrap")),
}
let cwd_path = match opt_text(cwd)? {
Some(c) => ctx.resolve_path(&c)?,
None => ctx.cwd.clone(),
};
if !cwd_path.is_dir() {
return Err(format!(
"session cwd is not a directory: {}",
cwd_path.display()
));
}
let session_timeout = parse_timeout(timeout, SESSION_TIMEOUT_SECS)?;
let mut command = Command::new(&argv[0]);
for a in &argv[1..] {
command.arg(a);
}
command.current_dir(&cwd_path);
command.stdin(Stdio::piped());
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
command.env("MARQDO_FOREIGN", "1");
command.env("MARQDO_FOREIGN_LANG", &canonical);
command.env("MARQDO_FOREIGN_CWD", &cwd_path);
for (k, v) in &spec.env {
command.env(k, v);
}
for (k, v) in parse_env(env)? {
command.env(k, v);
}
command.env("PYTHONUNBUFFERED", "1");
command.env("PYTHONIOENCODING", "utf-8");
command.env("PYTHONUTF8", "1");
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command.spawn().map_err(|e| {
format!(
"foreign session spawn failed (lang={canonical}, cmd={}): {e}",
argv[0]
)
})?;
let stdin = child
.stdin
.take()
.ok_or_else(|| "session stdin unavailable".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "session stdout unavailable".to_string())?;
let stderr_pipe = child.stderr.take();
let (tx, rx) = mpsc::channel::<String>();
let reader = thread::spawn(move || {
let mut reader = BufReader::new(stdout);
let mut line = String::new();
loop {
line.clear();
match reader.read_line(&mut line) {
Ok(0) => {
let _ = tx.send("__EOF__".into());
break;
}
Ok(_) => {
let _ = tx.send(line.trim_end_matches(['\r', '\n']).to_string());
}
Err(_) => {
let _ = tx.send("__EOF__".into());
break;
}
}
}
});
let stderr_buf = Arc::new(Mutex::new(String::new()));
let stderr_buf_t = Arc::clone(&stderr_buf);
let stderr_reader = thread::spawn(move || {
if let Some(mut r) = stderr_pipe {
let mut kept = Vec::new();
let mut buf = [0u8; 8192];
loop {
match r.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if kept.len() < MAX_PROCESS_STDERR {
let take = (MAX_PROCESS_STDERR - kept.len()).min(n);
kept.extend_from_slice(&buf[..take]);
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => break,
}
}
if let Ok(mut s) = stderr_buf_t.lock() {
s.push_str(&String::from_utf8_lossy(&kept));
}
}
});
let seq = ctx.foreign_session_seq + 1;
ctx.foreign_session_seq = seq;
let id = format!("s{seq}");
let started_ms = now_ms();
let cmd_display = argv[0].clone();
let session = Session {
id: id.clone(),
lang: canonical.clone(),
cmd: cmd_display.clone(),
started_ms,
timeout: session_timeout,
evals: 0,
alive: true,
child,
stdin,
rx,
_reader: reader,
stderr: stderr_buf,
_stderr_reader: stderr_reader,
};
ctx.foreign_sessions.insert(id.clone(), session);
let _ = timeout;
Ok(Value::Text(id))
}
fn session_dead_stderr(ctx: &HostContext, id: &str) -> String {
ctx.foreign_sessions
.get(id)
.and_then(|s| s.stderr.lock().ok().map(|v| v.clone()))
.unwrap_or_default()
}
fn remove_session(ctx: &mut HostContext, id: &str) {
ctx.foreign_sessions.remove(id);
}
pub fn eval(
ctx: &mut HostContext,
id: &Value,
code: Option<&Value>,
source: Option<&Value>,
input: Option<&Value>,
timeout: Option<&Value>,
) -> Result<Value, String> {
ensure_config(ctx);
let id = as_text(id, "id")?.to_string();
if !ctx.foreign_sessions.contains_key(&id) {
return Err(format!("foreign session `{id}` not found"));
}
let session_lang = ctx.foreign_sessions[&id].lang.clone();
let code = match (present(code), present(source)) {
(Some(_), Some(_)) => {
return Err("session_eval: pass either code or source, not both".into())
}
(Some(c), None) => match c {
Value::Code(b) => {
if crate::foreign::registry::canonical(&b.lang) != session_lang {
return Err(format!(
"session_eval code language `{}` does not match session language `{}`",
b.lang, session_lang
));
}
b.source.clone()
}
_ => return Err("session_eval code must be a code value".into()),
},
(None, Some(s)) => as_text(s, "source")?.to_string(),
(None, None) => return Err("session_eval needs code or source".into()),
};
let input_json = match input {
None | Some(Value::None) => serde_json::Value::Null,
Some(v) => value_to_json(v)?,
};
let default_timeout = ctx.foreign_sessions[&id].timeout.as_secs_f64();
let dur = parse_timeout(timeout, default_timeout)?;
let request = serde_json::json!({
"id": 1,
"op": "eval",
"code": code,
"input": input_json,
});
let start = Instant::now();
let (lang, cmd) = {
let s = &ctx.foreign_sessions[&id];
(s.lang.clone(), s.cmd.clone())
};
let reply = match send_and_wait(ctx, &id, &request, dur) {
Ok(r) => r,
Err(e) => {
let timed_out = e.contains("timed out");
let stderr = session_dead_stderr(ctx, &id);
remove_session(ctx, &id);
return Ok(record(
Some(&id),
&lang,
&cmd,
false,
String::new(),
stderr,
Value::None,
e,
start.elapsed().as_millis() as u64,
timed_out,
false,
));
}
};
let ms = start.elapsed().as_millis() as u64;
let alive = ctx
.foreign_sessions
.get_mut(&id)
.map(|s| {
s.evals += 1;
s.alive
})
.unwrap_or(false);
let ok = reply
.get("ok")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let stdout = reply
.get("stdout")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let stderr = reply
.get("stderr")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let error = reply
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let result = reply
.get("result")
.map(json_to_value)
.transpose()?
.unwrap_or(Value::None);
Ok(record(
Some(&id),
&lang,
&cmd,
ok,
stdout,
stderr,
result,
error,
ms,
false,
alive,
))
}
fn present(v: Option<&Value>) -> Option<&Value> {
match v {
None | Some(Value::None) => None,
Some(x) => Some(x),
}
}
fn send_and_wait(
ctx: &mut HostContext,
id: &str,
request: &serde_json::Value,
timeout: Duration,
) -> Result<serde_json::Value, String> {
let line = serde_json::to_string(request).map_err(|e| format!("session request: {e}"))?;
{
let session = ctx
.foreign_sessions
.get_mut(id)
.ok_or_else(|| format!("foreign session `{id}` not found"))?;
if let Ok(Some(_)) = session.child.try_wait() {
return Err("session process exited".into());
}
session
.stdin
.write_all(line.as_bytes())
.and_then(|_| session.stdin.write_all(b"\n"))
.and_then(|_| session.stdin.flush())
.map_err(|e| format!("session write: {e}"))?;
}
let deadline = Instant::now() + timeout;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
kill_session(ctx, id);
return Err(format!(
"session timed out after {:.3}s",
timeout.as_secs_f64()
));
}
let session = ctx
.foreign_sessions
.get_mut(id)
.ok_or_else(|| format!("foreign session `{id}` not found"))?;
match session.rx.recv_timeout(remaining.min(Duration::from_millis(200))) {
Ok(line) => {
if line == "__EOF__" {
return Err("session process exited".into());
}
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) {
let rid = v.get("id").and_then(|x| x.as_u64()).unwrap_or(0);
if rid != 1 {
continue;
}
return Ok(v);
}
// Unexpected non-protocol output: keep waiting until the deadline.
continue;
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if let Ok(Some(_)) = session.child.try_wait() {
return Err("session process exited".into());
}
continue;
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("session reader disconnected".into())
}
}
}
}
fn kill_session(ctx: &mut HostContext, id: &str) {
if let Some(mut s) = ctx.foreign_sessions.remove(id) {
#[cfg(unix)]
unsafe {
libc::kill(-(s.child.id() as i32), libc::SIGKILL);
}
let _ = s.child.kill();
let _ = s.child.wait();
s.alive = false;
}
}
pub fn set(
ctx: &mut HostContext,
id: &Value,
name: &Value,
value: &Value,
) -> Result<Value, String> {
let id = as_text(id, "id")?.to_string();
let name = as_text(name, "name")?.to_string();
if !valid_name(&name) {
return Err("session_set: name must be an identifier".into());
}
let json = value_to_json(value)?;
let request = serde_json::json!({"id": 1, "op": "set", "name": name, "value": json});
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
if reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
Ok(Value::None)
} else {
Err(reply
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("session_set failed")
.to_string())
}
}
pub fn get(ctx: &mut HostContext, id: &Value, name: &Value) -> Result<Value, String> {
let id = as_text(id, "id")?.to_string();
let name = as_text(name, "name")?.to_string();
if !valid_name(&name) {
return Err("session_get: name must be an identifier".into());
}
let request = serde_json::json!({"id": 1, "op": "get", "name": name});
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
return Err(reply
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("session_get failed")
.to_string());
}
match reply.get("result") {
Some(v) => json_to_value(v),
None => Ok(Value::None),
}
}
pub fn names(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = as_text(id, "id")?.to_string();
let request = serde_json::json!({"id": 1, "op": "names"});
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
return Err(reply
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("session_names failed")
.to_string());
}
match reply.get("result") {
Some(v) => json_to_value(v),
None => Ok(Value::List(Vec::new())),
}
}
pub fn close(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
let id = as_text(id, "id")?.to_string();
let existed = ctx.foreign_sessions.contains_key(&id);
kill_session(ctx, &id);
Ok(Value::Bool(existed))
}
pub fn list(ctx: &HostContext) -> Result<Value, String> {
let mut sessions: Vec<&Session> = ctx.foreign_sessions.values().collect();
sessions.sort_by(|a, b| a.id.cmp(&b.id));
let mut out = Vec::new();
for s in sessions {
out.push(Value::Map(vec![
("id".into(), Value::Text(s.id.clone())),
("lang".into(), Value::Text(s.lang.clone())),
("cmd".into(), Value::Text(s.cmd.clone())),
("evals".into(), Value::Int(s.evals as i64)),
("alive".into(), Value::Bool(s.alive)),
("started_ms".into(), Value::Int(s.started_ms)),
]));
}
Ok(Value::List(out))
}
pub fn shutdown(ctx: &mut HostContext) {
let ids: Vec<String> = ctx.foreign_sessions.keys().cloned().collect();
for id in ids {
kill_session(ctx, &id);
}
}
fn valid_name(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
_ => return false,
}
chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identifiers() {
assert!(valid_name("x"));
assert!(valid_name("_x1"));
assert!(!valid_name("1x"));
assert!(!valid_name("a-b"));
}
}
+14 -1
View File
@@ -34,6 +34,9 @@ fn text_body(v: &Value) -> Result<&str, String> {
pub fn read_text(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
if let Some(hit) = crate::host::sandbox_fs::cow_read_text(ctx, &p)? {
return Ok(Value::Text(hit));
}
let s = fs::read_to_string(&p).map_err(|e| format!("read_text {}: {e}", p.display()))?;
Ok(Value::Text(s))
}
@@ -43,10 +46,14 @@ pub fn write_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value
return Err("write_text denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
let body = text_body(text)?;
if crate::host::sandbox_fs::cow_write_text(ctx, &p, body)? {
return Ok(Value::None);
}
if let Some(parent) = p.parent() {
fs::create_dir_all(parent).map_err(|e| format!("write_text mkdir: {e}"))?;
}
fs::write(&p, text_body(text)?).map_err(|e| format!("write_text {}: {e}", p.display()))?;
fs::write(&p, body).map_err(|e| format!("write_text {}: {e}", p.display()))?;
Ok(Value::None)
}
@@ -68,6 +75,9 @@ pub fn append_text(ctx: &HostContext, path: &Value, text: &Value) -> Result<Valu
pub fn exists(ctx: &HostContext, path: &Value) -> Result<Value, String> {
let p = ctx.resolve_path(text_path(path)?)?;
if let Some(hit) = crate::host::sandbox_fs::cow_exists(ctx, &p)? {
return Ok(Value::Bool(hit));
}
Ok(Value::Bool(p.exists()))
}
@@ -109,6 +119,9 @@ pub fn remove(ctx: &HostContext, path: &Value) -> Result<Value, String> {
return Err("remove denied by host policy".into());
}
let p = ctx.resolve_path(text_path(path)?)?;
if crate::host::sandbox_fs::cow_remove(ctx, &p)? {
return Ok(Value::None);
}
if p.is_dir() {
fs::remove_dir_all(&p).map_err(|e| format!("remove {}: {e}", p.display()))?;
} else {
+28 -1
View File
@@ -14,6 +14,8 @@ mod encoding;
pub mod event_bus;
#[cfg(feature = "exec-host")]
pub mod foreign;
#[cfg(feature = "exec-host")]
pub mod foreign_session;
mod fs;
mod hash;
mod html_ops;
@@ -27,7 +29,7 @@ mod secrets;
mod stats;
mod text_ops;
mod time;
mod toml_ops;
pub(crate) mod toml_ops;
mod url_ops;
mod uuid_ops;
#[cfg(feature = "plugin-host")]
@@ -40,6 +42,7 @@ pub mod subtask;
#[cfg(not(feature = "exec-host"))]
#[path = "subtask_stub.rs"]
pub mod subtask;
pub mod sandbox_fs;
mod sys;
pub mod writeback;
@@ -92,6 +95,18 @@ pub struct HostContext {
pub plots: Vec<PlotArtifact>,
/// lang → interpreter argv (from `set_cmd`).
pub foreign_cmds: HashMap<String, Vec<String>>,
/// Process-local language registrations (`register` / `set_cmd`).
pub foreign_specs: HashMap<String, crate::foreign::registry::LangSpec>,
/// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime.
pub foreign_config_specs: HashMap<String, crate::foreign::registry::LangSpec>,
/// Whether project config has been discovered/loaded.
pub foreign_config_loaded: bool,
/// Persistent foreign kernels (`session_open`).
#[cfg(feature = "exec-host")]
pub foreign_sessions: HashMap<String, foreign_session::Session>,
/// Monotonic session id counter.
#[cfg(feature = "exec-host")]
pub foreign_session_seq: u64,
/// Loaded native plugins (ABI v1/v2).
pub plugins: PluginState,
/// Entry `.mq.md` source text (for ABI host_query / context injection).
@@ -111,6 +126,8 @@ pub struct HostContext {
pub subtask_seq: u64,
/// Minimum log level (`lib/log`); default Info (20). See `host::log::Level`.
pub log_min_level: u8,
/// Active `ext/ai/sandbox` CoW session id (nested `sandbox_run`).
pub sandbox_session: Option<String>,
}
impl Default for HostContext {
@@ -125,6 +142,13 @@ impl Default for HostContext {
rng: 0xC0FF_EE42_CAFE_BABE,
plots: Vec::new(),
foreign_cmds: HashMap::new(),
foreign_specs: HashMap::new(),
foreign_config_specs: HashMap::new(),
foreign_config_loaded: false,
#[cfg(feature = "exec-host")]
foreign_sessions: HashMap::new(),
#[cfg(feature = "exec-host")]
foreign_session_seq: 0,
plugins: PluginState::default(),
entry_source: None,
entry_path: None,
@@ -135,6 +159,7 @@ impl Default for HostContext {
subtasks: HashMap::new(),
subtask_seq: 0,
log_min_level: 20, // Info
sandbox_session: None,
}
}
}
@@ -142,6 +167,8 @@ impl Default for HostContext {
impl Drop for HostContext {
fn drop(&mut self) {
subtask::kill_all(self);
#[cfg(feature = "exec-host")]
foreign_session::shutdown(self);
}
}
+26 -3
View File
@@ -120,6 +120,9 @@ pub fn http_get(
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_get denied by host policy".into());
}
let url = as_text(url, "url")?;
@@ -137,6 +140,9 @@ pub fn http_post(
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_post denied by host policy".into());
}
let url = as_text(url, "url")?;
@@ -146,8 +152,13 @@ pub fn http_post(
Some(v) => as_text(v, "content_type")?,
};
let hdrs = headers_from_value(headers)?;
let (status, resp) = http_exchange("POST", url, Some(body), Some(ct), &hdrs)?;
Ok(response_map(status, resp))
// Transport failures → status 0 + body message (soft). Callers that need
// hard errors can still treat status!=200 as failure; Agent/LLM surfaces
// map this into structured `{finish:error}` instead of aborting the VM.
match http_exchange("POST", url, Some(body), Some(ct), &hdrs) {
Ok((status, resp)) => Ok(response_map(status, resp)),
Err(e) => Ok(response_map(0, e)),
}
}
/// Generic request: method + url + optional body / content_type / headers.
@@ -161,6 +172,9 @@ pub fn http_request(
headers: Option<&Value>,
) -> Result<Value, String> {
if !ctx.allow_net() {
if ctx.sandbox_session.is_some() {
return Err("net unavailable in sandbox".into());
}
return Err("http_request denied by host policy".into());
}
let method = as_text(method, "method")?.to_uppercase();
@@ -838,7 +852,16 @@ pub fn http_post_sse(
),
]))
}
Err(e) => Err(format!("http POST sse {url}: {e}")),
Err(e) => Ok(Value::Map(vec![
("status".into(), Value::Int(0)),
(
"events".into(),
Value::List(vec![event_map(vec![
("type", Value::Text("error".into())),
("message", Value::Text(format!("http POST sse {url}: {e}"))),
])]),
),
])),
}
}
+13
View File
@@ -417,6 +417,16 @@ unsafe extern "C" fn host_query(
});
Ok(serde_json::json!({ "ok": true }))
})(),
name if name.starts_with("sandbox_") => (|| {
let raw = args_owned.as_deref().unwrap_or("{}");
let args: serde_json::Value = serde_json::from_str(if raw.trim().is_empty() {
"{}"
} else {
raw
})
.map_err(|e| format!("{name} args: {e}"))?;
crate::host::sandbox_fs::query(name, &args, ctx)
})(),
// ADR 0007: run a Document/Endpoint `.mq.md` for HTTP handlers.
"run_artifact" => (|| {
let raw = args_owned.as_deref().unwrap_or("{}");
@@ -472,6 +482,9 @@ unsafe extern "C" fn host_query(
pub fn load(ctx: &mut HostContext, path: &Value) -> Result<Value, String> {
if !ctx.allow_plugin() {
if ctx.sandbox_session.is_some() {
return Err("plugin.load unavailable in sandbox".into());
}
return Err("plugin_load denied by host policy".into());
}
let rel = as_text(path, "path")?;
+475
View File
@@ -0,0 +1,475 @@
//! Application-level CoW workspace for `ext/ai/sandbox` (via host_query).
//!
//! lower = real root (read-through); upper = session bytes; whiteout = logical delete.
//! Not a symlink forest. Symlink targets are not followed as isolation primitives.
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use serde_json::json;
use crate::host::HostContext;
use crate::value::Value;
#[derive(Debug, Default)]
pub struct CowSession {
pub root: PathBuf,
/// Relative path (forward slashes) → file bytes.
pub upper: HashMap<String, Vec<u8>>,
pub whiteout: HashSet<String>,
}
static SESSIONS: OnceLock<Mutex<HashMap<String, CowSession>>> = OnceLock::new();
static SEQ: OnceLock<Mutex<u64>> = OnceLock::new();
fn sessions() -> &'static Mutex<HashMap<String, CowSession>> {
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn next_id() -> String {
let mut g = SEQ
.get_or_init(|| Mutex::new(0))
.lock()
.unwrap_or_else(|e| e.into_inner());
*g = g.wrapping_add(1);
format!("sbx-{g}")
}
fn normalize_rel(rel: &str) -> Result<String, String> {
let rel = rel.trim().trim_start_matches('/');
if rel.is_empty() {
return Err("sandbox path must not be empty".into());
}
let p = Path::new(rel);
if p.is_absolute() {
return Err("sandbox path must be relative to session root".into());
}
let mut out = Vec::new();
for c in p.components() {
match c {
Component::Normal(s) => out.push(s.to_string_lossy().into_owned()),
Component::CurDir => {}
Component::ParentDir => {
return Err("sandbox path must not contain '..'".into());
}
_ => return Err(format!("sandbox path invalid component in `{rel}`")),
}
}
if out.is_empty() {
return Err("sandbox path must not be empty".into());
}
Ok(out.join("/"))
}
fn abs_under_root(root: &Path, rel: &str) -> Result<PathBuf, String> {
let rel_n = normalize_rel(rel)?;
let abs = root.join(Path::new(&rel_n));
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
// Parent may not exist yet for writes — check by prefix components.
let mut check = abs.clone();
loop {
if check == *root || check == root_canon {
return Ok(root.join(Path::new(&rel_n)));
}
if !check.pop() {
break;
}
if let Ok(c) = check.canonicalize() {
if crate::host::path_under_root(&c, &root_canon) || c == root_canon {
return Ok(root.join(Path::new(&rel_n)));
}
}
}
if crate::host::path_under_root(&abs, root) {
return Ok(abs);
}
Err(format!("path escapes sandbox root: {rel_n}"))
}
pub fn open(root: Option<&str>, ctx: &HostContext) -> Result<serde_json::Value, String> {
let root_pb = if let Some(r) = root.filter(|s| !s.is_empty()) {
let p = PathBuf::from(r);
if p.is_absolute() {
p
} else {
ctx.cwd.join(p)
}
} else if let Some(ep) = &ctx.entry_path {
ep.parent()
.unwrap_or(ep.as_path())
.to_path_buf()
} else {
ctx.cwd.clone()
};
let root_pb = if root_pb.is_absolute() {
root_pb
} else {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(root_pb)
};
if !root_pb.is_dir() {
return Err(format!(
"sandbox_open: root is not a directory: {}",
root_pb.display()
));
}
let id = next_id();
let sess = CowSession {
root: root_pb.clone(),
upper: HashMap::new(),
whiteout: HashSet::new(),
};
sessions()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(id.clone(), sess);
Ok(json!({
"id": id,
"root": root_pb.to_string_lossy(),
}))
}
fn with_session_mut<F, T>(id: &str, f: F) -> Result<T, String>
where
F: FnOnce(&mut CowSession) -> Result<T, String>,
{
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
let sess = map
.get_mut(id)
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
f(sess)
}
fn with_session<F, T>(id: &str, f: F) -> Result<T, String>
where
F: FnOnce(&CowSession) -> Result<T, String>,
{
let map = sessions().lock().unwrap_or_else(|e| e.into_inner());
let sess = map
.get(id)
.ok_or_else(|| format!("sandbox: unknown session `{id}`"))?;
f(sess)
}
pub fn write(id: &str, path: &str, text: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let rel = normalize_rel(path)?;
let _ = abs_under_root(&sess.root, &rel)?;
sess.whiteout.remove(&rel);
sess.upper.insert(rel, text.as_bytes().to_vec());
Ok(json!({ "ok": true }))
})
}
pub fn read(id: &str, path: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
let rel = normalize_rel(path)?;
if sess.whiteout.contains(&rel) {
return Err(format!("sandbox_read: not found (whiteout): {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
let s = String::from_utf8(bytes.clone())
.map_err(|e| format!("sandbox_read: not utf-8: {e}"))?;
return Ok(json!(s));
}
let abs = abs_under_root(&sess.root, &rel)?;
let s = std::fs::read_to_string(&abs)
.map_err(|e| format!("sandbox_read {}: {e}", abs.display()))?;
Ok(json!(s))
})
}
pub fn remove(id: &str, path: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let rel = normalize_rel(path)?;
let _ = abs_under_root(&sess.root, &rel)?;
sess.upper.remove(&rel);
sess.whiteout.insert(rel);
Ok(json!({ "ok": true }))
})
}
pub fn diff(id: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
let mut items: Vec<serde_json::Value> = Vec::new();
for p in sess.upper.keys() {
items.push(json!({ "path": p, "kind": "write" }));
}
for p in &sess.whiteout {
items.push(json!({ "path": p, "kind": "remove" }));
}
items.sort_by(|a, b| {
let pa = a.get("path").and_then(|v| v.as_str()).unwrap_or("");
let pb = b.get("path").and_then(|v| v.as_str()).unwrap_or("");
pa.cmp(pb)
});
Ok(json!(items))
})
}
pub fn commit(id: &str) -> Result<serde_json::Value, String> {
with_session_mut(id, |sess| {
let mut applied = 0i64;
let writes: Vec<(String, Vec<u8>)> = sess
.upper
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let removes: Vec<String> = sess.whiteout.iter().cloned().collect();
for (rel, bytes) in writes {
let abs = abs_under_root(&sess.root, &rel)?;
if let Some(parent) = abs.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("sandbox_commit mkdir: {e}"))?;
}
std::fs::write(&abs, &bytes)
.map_err(|e| format!("sandbox_commit write {}: {e}", abs.display()))?;
applied += 1;
}
for rel in removes {
let abs = abs_under_root(&sess.root, &rel)?;
if abs.exists() {
if abs.is_dir() {
std::fs::remove_dir_all(&abs)
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
} else {
std::fs::remove_file(&abs)
.map_err(|e| format!("sandbox_commit remove {}: {e}", abs.display()))?;
}
applied += 1;
}
}
sess.upper.clear();
sess.whiteout.clear();
Ok(json!({ "ok": true, "applied": applied }))
})
}
pub fn discard(id: &str) -> Result<serde_json::Value, String> {
let mut map = sessions().lock().unwrap_or_else(|e| e.into_inner());
if map.remove(id).is_none() {
return Err(format!("sandbox: unknown session `{id}`"));
}
Ok(json!({ "ok": true }))
}
pub fn inspect(id: &str) -> Result<serde_json::Value, String> {
with_session(id, |sess| {
Ok(json!({
"id": id,
"root": sess.root.to_string_lossy(),
"upper_count": sess.upper.len(),
"whiteout_count": sess.whiteout.len(),
"caps_default": {
"fs_write": true,
"exec": false,
"net": false,
"plugin": false
},
"notes": [
"ext/web listen/DB/WS unavailable in sandbox",
"plugin.load denied during sandbox.run",
"subtask path/code/lang unavailable in sandbox"
]
}))
})
}
/// Read file bytes through CoW for an active host sandbox session (lib/fs).
pub fn cow_read_text(ctx: &HostContext, abs: &Path) -> Result<Option<String>, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(None);
};
with_session(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
if sess.whiteout.contains(&rel) {
return Err(format!("read_text: not found (sandbox whiteout): {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
let s = String::from_utf8(bytes.clone())
.map_err(|e| format!("read_text: not utf-8: {e}"))?;
return Ok(Some(s));
}
Ok(None)
})
}
pub fn cow_write_text(ctx: &HostContext, abs: &Path, text: &str) -> Result<bool, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(false);
};
with_session_mut(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
sess.whiteout.remove(&rel);
sess.upper.insert(rel, text.as_bytes().to_vec());
Ok(true)
})
}
pub fn cow_remove(ctx: &HostContext, abs: &Path) -> Result<bool, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(false);
};
with_session_mut(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
sess.upper.remove(&rel);
sess.whiteout.insert(rel);
Ok(true)
})
}
pub fn cow_exists(ctx: &HostContext, abs: &Path) -> Result<Option<bool>, String> {
let Some(id) = ctx.sandbox_session.as_deref() else {
return Ok(None);
};
with_session(id, |sess| {
let rel = rel_from_root(&sess.root, abs)?;
if sess.whiteout.contains(&rel) {
return Ok(Some(false));
}
if sess.upper.contains_key(&rel) {
return Ok(Some(true));
}
Ok(None)
})
}
fn rel_from_root(root: &Path, abs: &Path) -> Result<String, String> {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let abs_canon = abs.canonicalize().unwrap_or_else(|_| abs.to_path_buf());
let rel = abs_canon
.strip_prefix(&root_canon)
.or_else(|_| abs.strip_prefix(root))
.map_err(|_| format!("path not under sandbox root: {}", abs.display()))?;
normalize_rel(&rel.to_string_lossy().replace('\\', "/"))
}
pub fn run(
id: &str,
source: Option<&str>,
path: Option<&str>,
) -> Result<serde_json::Value, String> {
let (root, body) = with_session(id, |sess| {
let body = if let Some(src) = source.filter(|s| !s.trim().is_empty()) {
src.to_string()
} else if let Some(p) = path.filter(|s| !s.is_empty()) {
let rel = normalize_rel(p)?;
if sess.whiteout.contains(&rel) {
return Err(format!("sandbox_run: path whiteout: {rel}"));
}
if let Some(bytes) = sess.upper.get(&rel) {
String::from_utf8(bytes.clone())
.map_err(|e| format!("sandbox_run: path not utf-8: {e}"))?
} else {
let abs = abs_under_root(&sess.root, &rel)?;
std::fs::read_to_string(&abs)
.map_err(|e| format!("sandbox_run read {}: {e}", abs.display()))?
}
} else {
return Err("sandbox_run requires `source` or `path`".into());
};
Ok((sess.root.clone(), body))
})?;
let opts = crate::RunOptions {
allow_fs_write: true,
allow_exec: false,
allow_net: false,
allow_plugin: false,
fs_root: Some(root),
sandbox_session: Some(id.to_string()),
sleep_limit_ms: Some(0),
..crate::RunOptions::default()
};
match crate::run_source(&body, &opts) {
Ok(cap) => {
let value = crate::host::json::value_to_json(&cap.value)
.unwrap_or(serde_json::Value::Null);
Ok(json!({
"ok": true,
"value": value,
"stdout": cap.stdout,
}))
}
Err(e) => {
let msg = e.to_string();
Ok(json!({
"ok": false,
"error": msg,
"value": null,
"stdout": "",
}))
}
}
}
/// Parse host_query JSON args helper used from plugin.rs.
pub fn query(name: &str, args: &serde_json::Value, ctx: &HostContext) -> Result<serde_json::Value, String> {
let id = || {
args.get("id")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("{name}: missing `id`"))
};
match name {
"sandbox_open" => {
let root = args.get("root").and_then(|v| v.as_str());
open(root, ctx)
}
"sandbox_write" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_write: missing `path`".to_string())?;
let text = args
.get("text")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_write: missing `text`".to_string())?;
write(id()?, path, text)
}
"sandbox_read" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_read: missing `path`".to_string())?;
read(id()?, path)
}
"sandbox_remove" => {
let path = args
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| "sandbox_remove: missing `path`".to_string())?;
remove(id()?, path)
}
"sandbox_diff" => diff(id()?),
"sandbox_commit" => commit(id()?),
"sandbox_discard" => discard(id()?),
"sandbox_inspect" => inspect(id()?),
"sandbox_run" => {
let source = args.get("source").and_then(|v| v.as_str());
let path = args.get("path").and_then(|v| v.as_str());
run(id()?, source, path)
}
other => Err(format!("sandbox query unknown `{other}`")),
}
}
#[allow(dead_code)]
pub fn unavailable(feature: &str) -> String {
format!("{feature} unavailable in sandbox")
}
/// Used by fs layer when session is active — map Value path through resolve then CoW.
pub fn try_read_value(ctx: &HostContext, path: &Value) -> Result<Option<Value>, String> {
let rel = match path {
Value::Text(s) => s.as_str(),
_ => return Ok(None),
};
let abs = ctx.resolve_path(rel)?;
match cow_read_text(ctx, &abs)? {
Some(s) => Ok(Some(Value::Text(s))),
None => Ok(None),
}
}
+13 -7
View File
@@ -120,8 +120,8 @@ fn republish_child_event(line: &str) {
pub(crate) struct ForeignTask {
child: Child,
temp_script: PathBuf,
stdout: JoinHandle<String>,
stderr: JoinHandle<String>,
stdout: JoinHandle<(String, bool)>,
stderr: JoinHandle<(String, bool)>,
}
enum FnState {
@@ -392,6 +392,9 @@ fn spawn_fn(
let cwd = ctx.cwd.clone();
let caps = ctx.caps.clone();
let foreign_cmds = ctx.foreign_cmds.clone();
let foreign_specs = ctx.foreign_specs.clone();
let foreign_config_specs = ctx.foreign_config_specs.clone();
let foreign_config_loaded = ctx.foreign_config_loaded;
let fs_root = ctx.fs_root.clone();
let argv = ctx.argv.clone();
@@ -407,6 +410,9 @@ fn spawn_fn(
host.fs_root = fs_root;
host.argv = argv;
host.foreign_cmds = foreign_cmds;
host.foreign_specs = foreign_specs;
host.foreign_config_specs = foreign_config_specs;
host.foreign_config_loaded = foreign_config_loaded;
host.set_entry_source(Some(&module_path), &source);
host.entry_metadata = module.metadata.clone();
let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host);
@@ -587,12 +593,9 @@ fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
.child
.wait()
.map_err(|e| format!("subtask foreign join: {e}"))?;
let stdout = task.stdout.join().unwrap_or_default();
let stderr = task.stderr.join().unwrap_or_default();
let (stdout, out_trunc) = task.stdout.join().unwrap_or_default();
let (stderr, err_trunc) = task.stderr.join().unwrap_or_default();
let _ = std::fs::remove_file(&task.temp_script);
if stdout.len() > foreign::MAX_OUTPUT || stderr.len() > foreign::MAX_OUTPUT {
return Err("subtask foreign output too large".into());
}
if !status.success() {
let code = status.code().unwrap_or(1);
let mut msg = format!("subtask foreign failed (exit={code})");
@@ -609,6 +612,9 @@ fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
out.pop();
}
}
if out_trunc || err_trunc {
out.push_str("\n…(truncated)");
}
Ok(Value::Text(out))
}
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more