Refactor executable library handbooks and improve document reading

This commit is contained in:
cflmy committed 2026-11-08 22:19:11 +08:00
1 parent 16c44588d5
commit c50c515c4a
191 files changed
+29572 -7816

No files matched your search

+3435 -1930
View File
File diff suppressed because it is too large. Load diff
+72
View File
@@ -0,0 +1,72 @@
---
markup: occlusion
title: AI workflows — model adapters, agents, workbooks and trials
import:
model_api: ext/ai/llm.mq.md
---
Start here to choose an AI task. [Model calls](llm.mq.md) own prompts, model configuration,
stream collection and usage; [provider adapters](llm/index.mq.md) describe OpenAI-compatible
and Ollama requests. [Agents](agent.mq.md) own call-site context, the explicit tool registry,
policy routing, observations, workbook planning and continuation. [CoW trials](sandbox.mq.md)
own isolated file changes and promotion. [Step routing](policies/step-route.mq.md) is readable
policy data, not a second agent language. Chinese users can start at [索引](索引.mq.md).
Begin with this offline stream example; it does not request credentials, install a plugin or
contact a model. Commands run from the repository root:
```sh
marqdo call ext/ai/index.mq.md offline_example --json
```
For a live model call, configure its provider and credentials before invoking the existing llm
resource. A configured language or adapter does not prove a remote endpoint is available.
Agent operations require the native agent plugin, an explicit model and the permitted tools;
use cargo build -p marqdo_plugin_agent in this checkout. Never let a generated CALL line select
an arbitrary internal function. File, process and network permissions remain bounded by the host.
Develop one responsibility at a time: provider request shaping belongs under llm/, common model
state in llm.mq.md, planner orchestration in agent.mq.md and trial behavior in sandbox.mq.md.
Keep the agent's call-site and source budgets intact when changing its internal helpers; moving
an operation can affect context and replay. Review effect preparation, transitions and saved
results before adding retries, and do not repeat writes merely to reconstruct a checkpoint.
Use deterministic stream fixtures and local provider substitutes before live tests. Verify text,
usage, failed tools, lost responses, cancellation, context limits and durable continuation;
model output is data until an authorized tool target and arguments have been resolved.
## collect_events
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| events | list | required | Ordered semantic or supported provider stream-event records |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | text | Final text assembled by the public stream collector |
The supplied `events` are an already-observed stream, not instructions to request a new model
response or execute a tool. The shared collector understands delta/text, done.result and its
existing provider-frame conventions. We return *[Collect the existing stream into final text](model_api.collect(events=`events`))*
so offline processing and live transport use the same public assembly behavior.
## offline_example
| 返回 | 类型 | 说明 |
|---|---|---|
| result | text | Hello world, assembled from actual semantic events without a model request |
The event table is a deterministic stream fixture. A delta introduces partial text, then the
final done result supplies the completed answer. Passing these through the public collector
verifies useful behavior; this tool does not manufacture a passed flag or a fake model answer.
`events` =
| @ | type | text | result |
|---|---|---|---|
| 1 | delta | "Hello " | None |
| 2 | done | None | "Hello world" |
We return *[Assemble the final text from the displayed stream](collect_events(events=`events`))*.
A real transport failure still needs its domain error handling; this fixture only demonstrates
stream assembly, and it deliberately performs no network operation.
+355 -191
View File
@@ -13,68 +13,88 @@ import:
openai: ext/ai/llm/openai.mq.md
---
Choose the public model resource here for ask, stream and collected response behavior. [The AI entry](index.mq.md) provides an offline event workflow; [the adapter entry](llm/index.mq.md) owns provider configuration and transport shapes. Agents and workbook orchestration belong in agent.mq.md. A created handle is configuration, not proof that authentication or a model request succeeded. Keep transport errors, semantic events and usage counters visible when extending this file.
## load_env
+ `path`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Load `.env` from cwd (optional `path=`). Does not override existing variables. |
Use `path`=None as the inputs for this operation.
Load `.env` from cwd (optional `path=`). Does not override existing variables.
*> sys.load_dotenv path=`path`*
Return *[Load dotenv](sys.load_dotenv(path=`path`))*.
## collect
+ `events`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| events | any | required | Ordered semantic or provider stream-event records |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Collapse a stream event list to final answer text. Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`). Alias: `stream_result`. |
Use `events` as the inputs for this operation.
Collapse a stream event list to final answer text.
Accepts semantic events (`delta` / `text` / `done.result` / `error.message`) and
native-plugin raw SSE frames (`type=data` with OpenAI chunk JSON in `data`).
Alias: `stream_result`.
**answer = ""**
We retain **answer = ""**.
- [ev](遍历 events 为 ev)
**t = > json.get value=`ev` key="type"**
We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**.
1. `t` == "done"
**done_r = > json.get value=`ev` key="result"**
We retain **`done_r` = [Read the result field](json.get(value=`ev`, key="result"))**.
1. `done_r`
**answer = `done_r`**
We retain **answer = `done_r`**.
2. *
**_ = 1**
2. `t` == "error"
**em = > json.get value=`ev` key="message"**
We retain **`em` = [Read the message field](json.get(value=`ev`, key="message"))**.
1. `em`
**answer = `em`**
We retain **answer = `em`**.
2. *
**_ = 1**
3. `t` == "delta"
4. `t` == "text"
**chunk = > json.get value=`ev` key="text"**
We retain **`chunk` = [Read the text field](json.get(value=`ev`, key="text"))**.
1. `chunk`
**answer = answer + chunk**
We retain **answer = answer + chunk**.
2. *
**_ = 1**
5. `t` == "data"
**raw = > json.get value=`ev` key="data"**
We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**.
1. `raw`
1. `raw` == "[DONE]"
**_ = 1**
2. *
**parsed = > json.parse text=`raw`**
We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**.
1. `parsed`
**choices = > json.get value=`parsed` key="choices"**
We retain **`choices` = [Read the choices field](json.get(value=`parsed`, key="choices"))**.
1. `choices`
**c0 = [1](access(choices, "1"))**
**delta = > json.get value=`c0` key="delta"**
We retain **`c0` = [Read 1 field](access(`choices`, "1"))**.
We retain **`delta` = [Read the delta field](json.get(value=`c0`, key="delta"))**.
1. `delta`
**piece = > json.get value=`delta` key="content"**
We retain **`piece` = [Read the content field](json.get(value=`delta`, key="content"))**.
1. `piece`
**answer = answer + piece**
We retain **answer = answer + piece**.
2. *
**_ = 1**
2. *
**msg = > json.get value=`c0` key="message"**
We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**.
1. `msg`
**piece = > json.get value=`msg` key="content"**
We retain **`piece` = [Read the content field](json.get(value=`msg`, key="content"))**.
1. `piece`
**answer = answer + piece**
We retain **answer = answer + piece**.
2. *
**_ = 1**
2. *
@@ -89,173 +109,272 @@ Alias: `stream_result`.
**_ = 1**
1. not `answer`
**answer = ""**
*answer*
We retain **answer = ""**.
Return *answer*.
## collect_usage
+ `events`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| events | any | required | Ordered semantic or provider stream-event records |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`). |
Use `events` as the inputs for this operation.
Best-effort `total_tokens` from stream frames (requires `stream_options.include_usage`).
**tokens = None**
We retain **tokens = None**.
1. `events`
- [ev](遍历 events 为 ev)
**t = > json.get value=`ev` key="type"**
**raw = None**
We retain **`t` = [Read the type field](json.get(value=`ev`, key="type"))**.
We retain **raw = None**.
1. `t` == "data"
**raw = > json.get value=`ev` key="data"**
We retain **`raw` = [Read the data field](json.get(value=`ev`, key="data"))**.
2. *
**u0 = > json.get value=`ev` key="usage"**
We retain **`u0` = [Read the usage field](json.get(value=`ev`, key="usage"))**.
1. `u0`
**tt0 = > json.get value=`u0` key="total_tokens"**
We retain **`tt0` = [Read the total_tokens field](json.get(value=`u0`, key="total_tokens"))**.
1. `tt0` != None
**tokens = `tt0`**
We retain **tokens = `tt0`**.
1. `raw`
1. not `raw` == "[DONE]"
**parsed = > json.parse text=`raw`**
We retain **`parsed` = [Parse the JSON transport text](json.parse(text=`raw`))**.
1. `parsed`
**u = > json.get value=`parsed` key="usage"**
We retain **`u` = [Read the usage field](json.get(value=`parsed`, key="usage"))**.
1. `u`
**tt = > json.get value=`u` key="total_tokens"**
We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**.
1. `tt` != None
**tokens = `tt`**
*tokens*
We retain **tokens = `tt`**.
Return *tokens*.
## stream_result
+ `events`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| events | any | required | Ordered semantic or provider stream-event records |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Compatibility alias for `collect`. |
Use `events` as the inputs for this operation.
Compatibility alias for `collect`.
*> collect events=`events`*
Return *[Collect](collect(events=`events`))*.
## usage_from
+ `data`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros). |
Use `data` as the inputs for this operation.
Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map (or empty zeros).
*> openai.usage_from data=`data`*
Return *[Usage from](openai.usage_from(data=`data`))*.
## create
+ `model`=None
+ `base_url`=None
+ `api_key`=None
+ `backend`=openai-compatible
+ `name`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| backend | any | "openai-compatible" | Configured execution or provider backend |
| name | any | None | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`). |
Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation.
Factory for an LLM handle (same as constructing `# llm`). Env fallbacks apply inside the constructor. Optional `name=` tags the handle (`fast` / `reasoning`).
**h = > llm model=`model` base_url=`base_url` api_key=`api_key` backend=`backend` name=`name`**
*h*
We retain **`h` = [Llm](llm(model=`model`, base_url=`base_url`, api_key=`api_key`, backend=`backend`, name=`name`))**.
Return *h*.
## fast
+ `model`=None
+ `base_url`=None
+ `api_key`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model. |
Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation.
Named small/fast handle. Model from arg, else `MARQDO_LLM_FAST_MODEL`, else default create model.
1. `model`
**mdl = `model`**
We retain **mdl = `model`**.
2. *
**mdl = > sys.env_get name="MARQDO_LLM_FAST_MODEL"**
We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_FAST_MODEL"))**.
*> create model=`mdl` base_url=`base_url` api_key=`api_key` name="fast" backend="openai-compatible"*
Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="fast", backend="openai-compatible"))*.
## reasoning
+ `model`=None
+ `base_url`=None
+ `api_key`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model. |
Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation.
Named strong/reasoning handle. Model from arg, else `MARQDO_LLM_REASONING_MODEL`, else default create model.
1. `model`
**mdl = `model`**
We retain **mdl = `model`**.
2. *
**mdl = > sys.env_get name="MARQDO_LLM_REASONING_MODEL"**
We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_REASONING_MODEL"))**.
*> create model=`mdl` base_url=`base_url` api_key=`api_key` name="reasoning" backend="openai-compatible"*
Return *[Create](create(model=`mdl`, base_url=`base_url`, api_key=`api_key`, name="reasoning", backend="openai-compatible"))*.
## prompt_body
+ `src`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| src | any | required | Prompt source or source-reference value |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged. |
Use `src` as the inputs for this operation.
If `src` starts with YAML frontmatter declaring `type: prompt` / `类型: 提示`, return the body after the closing `---`; otherwise return `src` unchanged.
**sw = > text.starts_with text=`src` prefix="---"**
We retain **`sw` = [Starts with](text.starts_with(text=`src`, prefix="---"))**.
1. not `sw`
*src*
Return *src*.
2. *
**parts = > split value=`src` sep="\n---\n"**
**n = > len value=`parts`**
We retain **`parts` = [Split](split(value=`src`, sep="\n---\n"))**.
We retain **`n` = [Len](len(value=`parts`))**.
1. `n` < 2
*src*
Return *src*.
2. *
**fm = > at value=`parts` index=0**
**is_p = > text.contains text=`fm` sub="type: prompt"**
We retain **`fm` = [At](at(value=`parts`, index=0))**.
We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="type: prompt"))**.
1. not `is_p`
**is_p = > text.contains text=`fm` sub="类型: 提示"**
We retain **`is_p` = [Contains](text.contains(text=`fm`, sub="类型: 提示"))**.
2. *
**_ = 1**
1. `is_p`
**body = > at value=`parts` index=1**
*> text.str_trim s=`body`*
We retain **`body` = [At](at(value=`parts`, index=1))**.
Return *[Str trim](text.str_trim(s=`body`))*.
2. *
*src*
Return *src*.
## prompt_load
+ `path`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`. |
Use `path` as the inputs for this operation.
Load a prompt artifact (`.mq.md` / `.md`) from disk for `ask`.
**raw = > fs.read_text path=`path`**
*> prompt_body src=`raw`*
We retain **`raw` = [Read UTF-8 text from the selected file](fs.read_text(path=`path`))**.
Return *[Prompt body](prompt_body(src=`raw`))*.
## prompt
+ `path`=None
+ `text`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| text | any | None | Text supplied to the transformation or adapter |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string. |
Use `path`=None, `text`=None as the inputs for this operation.
Prompt artifact helper: `path=` loads a file; `text=` strips `type: prompt` frontmatter from an in-memory string.
1. `path`
*> prompt_load path=`path`*
Return *[Prompt load](prompt_load(path=`path`))*.
2. `text`
*> prompt_body src=`text`*
Return *[Prompt body](prompt_body(src=`text`))*.
3. *
> print text=ext/ai/llm.prompt: pass path= or text=
> sys.exit code=1
We **[Print the prepared message](print(text="ext/ai/llm.prompt: pass", path="or", text=""))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
## ask
+ `prompt`=None
+ `path`=None
+ `model`=None
+ `base_url`=None
+ `api_key`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | None | Prompt text or structured prompt expected by this adapter |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`). |
Use `prompt`=None, `path`=None, `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation.
Module convenience: create a default handle and return **answer text**. Pass `path=` to load a prompt document, `prompt=` text, or omit both to use the entry `.mq.md` as a prompt artifact (`type: prompt` body via `sys.module_source`).
**p = `prompt`**
We retain **p = `prompt`**.
1. `path`
**p = > prompt_load path=`path`**
We retain **`p` = [Prompt load](prompt_load(path=`path`))**.
2. `prompt`
**p = `prompt`**
We retain **p = `prompt`**.
3. *
**raw = > sys.module_source**
We retain **`raw` = [Module source](sys.module_source())**.
1. not `raw`
> print text=ext/ai/llm.ask: pass prompt= or path= (or run a prompt document as entry)
> sys.exit code=1
We **[Print the prepared message](print(text="ext/ai/llm.ask: pass", prompt="or", path="(or run a prompt document as entry)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
2. *
**p = > prompt_body src=`raw`**
We retain **`p` = [Prompt body](prompt_body(src=`raw`))**.
**m = > create model=`model` base_url=`base_url` api_key=`api_key`**
**r = > m.ask prompt=`p`**
**_ret = > json.get value=`r` key="text"**
*_ret*
We retain **`m` = [Create](create(model=`model`, base_url=`base_url`, api_key=`api_key`))**.
We retain **`r` = [Ask](m.ask(prompt=`p`))**.
We retain **`_ret` = [Read the text field](json.get(value=`r`, key="text"))**.
Return *_ret*.
# llm
+ `model`=None
+ `base_url`=None
+ `api_key`=None
+ `backend`=openai-compatible
+ `name`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| backend | any | "openai-compatible" | Configured execution or provider backend |
| name | any | None | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | LLM handle — intelligence primitive, not an HTTP client. Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`) → `sys.env_get` → defaults. Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names. |
Use `model`=None, `base_url`=None, `api_key`=None, `backend`="openai-compatible", `name`=None as the inputs for this operation.
LLM handle — intelligence primitive, not an HTTP client.
@@ -263,13 +382,13 @@ Resolution: explicit args → entry-scope / Artifact Metadata (`sys.meta_get`)
Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then use the lifted names.
1. `api_key`
**key = `api_key`**
We retain **key = `api_key`**.
2. *
**key = > sys.meta_get key="api_key"**
We retain **`key` = [Meta get](sys.meta_get(key="api_key"))**.
1. not `key`
**key = > sys.env_get name="OPENAI_API_KEY"**
We retain **`key` = [Env get](sys.env_get(name="OPENAI_API_KEY"))**.
1. not `key`
**key = > sys.env_get name="MARQDO_LLM_API_KEY"**
We retain **`key` = [Env get](sys.env_get(name="MARQDO_LLM_API_KEY"))**.
2. *
**_ = 1**
2. *
@@ -277,62 +396,62 @@ Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then u
1. `backend` == ollama
1. not `key`
**key = "ollama"**
We retain **key = "ollama"**.
2. *
**_ = 1**
2. not `key`
> print text=ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY (or pass api_key= / metadata api_key)
> sys.exit code=1
We **[Print the prepared message](print(text="ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY (or pass api_key= / metadata api_key)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
3. *
**_ = 1**
1. `base_url`
**url = `base_url`**
We retain **url = `base_url`**.
2. *
**url = > sys.meta_get key="base_url"**
We retain **`url` = [Meta get](sys.meta_get(key="base_url"))**.
1. `url`
**_ = 1**
2. `backend` == ollama
**url = > sys.env_get name="OLLAMA_HOST"**
We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**.
1. not `url`
**url = "http://127.0.0.1:11434/v1"**
We retain **url = "http://127.0.0.1:11434/v1"**.
2. *
**_ = 1**
3. *
**url = > sys.env_get name="OPENAI_BASE_URL"**
We retain **`url` = [Env get](sys.env_get(name="OPENAI_BASE_URL"))**.
1. not `url`
**url = > sys.env_get name="MARQDO_LLM_BASE_URL"**
We retain **`url` = [Env get](sys.env_get(name="MARQDO_LLM_BASE_URL"))**.
2. *
**_ = 1**
1. not `url`
**url = "https://api.openai.com/v1"**
We retain **url = "https://api.openai.com/v1"**.
2. *
**_ = 1**
1. `model`
**mdl = `model`**
We retain **mdl = `model`**.
2. *
**mdl = > sys.meta_get key="model"**
We retain **`mdl` = [Meta get](sys.meta_get(key="model"))**.
1. `mdl`
**_ = 1**
2. *
**mdl = > sys.env_get name="OPENAI_MODEL"**
We retain **`mdl` = [Env get](sys.env_get(name="OPENAI_MODEL"))**.
1. not `mdl`
**mdl = > sys.env_get name="MARQDO_LLM_MODEL"**
We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**.
2. *
**_ = 1**
1. not `mdl`
1. `backend` == ollama
**mdl = "llama3.2"**
We retain **mdl = "llama3.2"**.
2. *
**mdl = "gpt-4o-mini"**
We retain **mdl = "gpt-4o-mini"**.
2. *
**_ = 1**
1. `name`
**nm = `name`**
We retain **nm = `name`**.
2. *
**nm = None**
We retain **nm = None**.
`h` =
@@ -340,49 +459,58 @@ Prefer declaring `model` / `api_key` / `base_url` in frontmatter Binding, then u
|-------|---------|---------|----------|-------|--------|--------|------|
| llm | `backend` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` |
*h*
Return *h*.
## ask
+ `prompt`=None
+ `path`=None
+ `messages`=None
+ `selection`=None
+ `strict_selection`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | None | Prompt text or structured prompt expected by this adapter |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| messages | any | None | Ordered chat message records |
| selection | any | None | Explicit runtime/model selection |
| strict_selection | any | False | Whether an unresolved selection is an error |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback. |
Use `prompt`=None, `path`=None, `messages`=None, `selection`=None, `strict_selection`=False as the inputs for this operation.
Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `name`, `tool_calls`). Prefer `[text](result)` for the answer string. Omit `prompt=` / `path=` to use the entry document (`sys.module_source` + `prompt_body`). Pass `messages=` for multi-turn history (M01). `selection=` + `strict_selection=True` freeze request identity without env fallback.
**p = `prompt`**
We retain **p = `prompt`**.
1. `messages`
**p = None**
We retain **p = None**.
2. `path`
**p = > prompt_load path=`path`**
We retain **`p` = [Prompt load](prompt_load(path=`path`))**.
3. `prompt`
**p = `prompt`**
We retain **p = `prompt`**.
4. *
**raw = > sys.module_source**
We retain **`raw` = [Module source](sys.module_source())**.
1. not `raw`
**p = ""**
We retain **p = ""**.
2. *
**p = > prompt_body src=`raw`**
**pack = > self.complete_result prompt=`p` messages=`messages` selection=`selection` strict_selection=`strict_selection` stream=False echo=False**
**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"**
We retain **`p` = [Prompt body](prompt_body(src=`raw`))**.
We retain **`pack` = [Complete result](self.complete_result(prompt=`p`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=False, echo=False))**.
We retain **`text` = [Read the text field](json.get(value=`pack`, key="text"))**.
We retain **`usage` = [Read the usage field](json.get(value=`pack`, key="usage"))**.
We retain **`finish` = [Read the finish field](json.get(value=`pack`, key="finish"))**.
We retain **`err` = [Read the error field](json.get(value=`pack`, key="error"))**.
We retain **`tc` = [Read the tool_calls field](json.get(value=`pack`, key="tool_calls"))**.
1. not `tc`
**tc = > table.empty_list**
We retain **`tc` = [Empty list](table.empty_list())**.
2. *
**_ = 1**
1. not `text`
**text = ""**
We retain **text = ""**.
2. *
**_ = 1**
1. not `finish`
1. `err`
**finish = "error"**
We retain **finish = "error"**.
2. *
**finish = "stop"**
We retain **finish = "stop"**.
2. *
**_ = 1**
@@ -390,26 +518,26 @@ 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 = > json.get value=`self` key="model"**
**b = > json.get value=`self` key="backend"**
**nm = > json.get value=`self` key="name"**
We retain **`mdl` = [Read the model field](json.get(value=`self`, key="model"))**.
We retain **`b` = [Read the backend field](json.get(value=`self`, key="backend"))**.
We retain **`nm` = [Read the name field](json.get(value=`self`, key="name"))**.
1. `usage`
**tt = > json.get value=`usage` key="total_tokens"**
**ustate = > json.get value=`usage` key="usage_state"**
We retain **`tt` = [Read the total_tokens field](json.get(value=`usage`, key="total_tokens"))**.
We retain **`ustate` = [Read the usage_state field](json.get(value=`usage`, key="usage_state"))**.
2. *
**tt = None**
**ustate = "unknown"**
We retain **tt = None**.
We retain **ustate = "unknown"**.
1. `ustate` == "unknown"
Keep null — never coerce missing usage to zero tokens (M02 / F04).
**tt = None**
We retain **tt = None**.
2. not `tt`
**tt = None**
We retain **tt = None**.
3. *
**_ = 1**
1. `err`
**calls = 0**
We retain **calls = 0**.
2. *
**calls = 1**
We retain **calls = 1**.
`result` =
@@ -417,66 +545,102 @@ inside the table is unsafe.
|------|-------|--------|---------|-------|------|-----------|--------|------------|-------|-----------|
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | `calls` | `tt` | `tc` | `err` | `selection` |
*result*
Return *result*.
## stream
+ `prompt`=None
+ `path`=None
+ `echo`=False
+ `stream_kind`="delta"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | None | Prompt text or structured prompt expected by this adapter |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| echo | any | False | Whether to print the documented incremental output |
| stream_kind | any | "delta" | Streaming event projection selected by the caller |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document. |
Use `prompt`=None, `path`=None, `echo`=False, `stream_kind`="delta" as the inputs for this operation.
Semantic stream: return the event list (use `llm.collect` to reduce to text). Omit `prompt=` / `path=` to use the entry document.
`stream_kind=plan` tags EventBus frames for the parent plan protocol (process trail).
1. `path`
**p = > prompt_load path=`path`**
We retain **`p` = [Prompt load](prompt_load(path=`path`))**.
2. `prompt`
**p = `prompt`**
We retain **p = `prompt`**.
3. *
**raw = > sys.module_source**
We retain **`raw` = [Module source](sys.module_source())**.
1. not `raw`
**p = ""**
We retain **p = ""**.
2. *
**p = > prompt_body src=`raw`**
We retain **`p` = [Prompt body](prompt_body(src=`raw`))**.
*> self.complete prompt=`p` stream=True echo=`echo` stream_kind=`stream_kind`*
Return *[Complete](self.complete(prompt=`p`, stream=True, echo=`echo`, stream_kind=`stream_kind`))*.
## complete_result
+ `prompt`=None
+ `messages`=None
+ `selection`=None
+ `strict_selection`=False
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | None | Prompt text or structured prompt expected by this adapter |
| messages | any | None | Ordered chat message records |
| selection | any | None | Explicit runtime/model selection |
| strict_selection | any | False | Whether an unresolved selection is an error |
| stream | any | False | Whether to preserve streaming behavior or emit stream events |
| echo | any | False | Whether to print the documented incremental output |
| stream_kind | any | "delta" | Streaming event projection selected by the caller |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01). |
Use `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation.
Transport pack via `ext/ai/llm/openai` (Ollama uses the same OpenAI-compatible path). Non-stream → `{text,usage,finish}`; stream → `{events}`. Prefer `messages=` for multi-turn; optional `selection=` (ModelSelectionV1) with `strict_selection=True` for request-scoped identity (M01).
*> openai.chat_completions base_url=[base_url](access(self, "base_url")) api_key=[api_key](access(self, "api_key")) model=[model](access(self, "model")) prompt=`prompt` messages=`messages` selection=`selection` strict_selection=`strict_selection` stream=`stream` echo=`echo` stream_kind=`stream_kind` suffix=[suffix](access(self, "suffix")) bearer=[bearer](access(self, "bearer"))*
Return *[Chat completions](openai.chat_completions(base_url=[base_url](access(`self`, "base_url")), api_key=[api_key](access(`self`, "api_key")), model=[model](access(`self`, "model")), prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=[suffix](access(`self`, "suffix")), bearer=[bearer](access(`self`, "bearer"))))*.
## complete
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | required | Prompt text or structured prompt expected by this adapter |
| stream | any | False | Whether to preserve streaming behavior or emit stream events |
| echo | any | False | Whether to print the documented incremental output |
| stream_kind | any | "delta" | Streaming event projection selected by the caller |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Internal / compatibility primitive. Prefer `ask` / `stream` in new code. |
Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation.
Internal / compatibility primitive. Prefer `ask` / `stream` in new code.
1. `stream`
**pack = > self.complete_result prompt=`prompt` stream=True echo=`echo` stream_kind=`stream_kind`**
**_ret = > json.get value=`pack` key="events"**
*_ret*
We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=True, echo=`echo`, stream_kind=`stream_kind`))**.
We retain **`_ret` = [Read the events field](json.get(value=`pack`, key="events"))**.
Return *_ret*.
2. *
**pack = > self.complete_result prompt=`prompt` stream=False echo=`echo` stream_kind=`stream_kind`**
**_ret = > json.get value=`pack` key="text"**
*_ret*
We retain **`pack` = [Complete result](self.complete_result(prompt=`prompt`, stream=False, echo=`echo`, stream_kind=`stream_kind`))**.
We retain **`_ret` = [Read the text field](json.get(value=`pack`, key="text"))**.
Return *_ret*.
## chat
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prompt | any | required | Prompt text or structured prompt expected by this adapter |
| stream | any | False | Whether to preserve streaming behavior or emit stream events |
| echo | any | False | Whether to print the documented incremental output |
| stream_kind | any | "delta" | Streaming event projection selected by the caller |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Alias for `complete` (compat). |
Use `prompt`, `stream`=False, `echo`=False, `stream_kind`="delta" as the inputs for this operation.
Alias for `complete` (compat).
*> self.complete prompt=`prompt` stream=`stream` echo=`echo` stream_kind=`stream_kind`*
Return *[Complete](self.complete(prompt=`prompt`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`))*.
+60
View File
@@ -0,0 +1,60 @@
---
markup: occlusion
title: Provider adapters — requests, configuration and usage
import:
ollama: ext/ai/llm/ollama.mq.md
openai: ext/ai/llm/openai.mq.md
---
This directory owns provider adaptation. [OpenAI-compatible requests](openai.mq.md) encode chat
messages, decode replies and usage, and retain streaming/error conventions. [Ollama](ollama.mq.md)
selects its documented local defaults while reusing compatible transport. The parent [model API](../llm.mq.md)
creates author model resources; [the AI root](../index.mq.md) explains agent and trial responsibilities.
This offline usage example inspects response data only. It does not read credentials, load a
plugin or contact the provider:
```sh
marqdo call ext/ai/llm/index.mq.md usage 'data={"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}' --json
```
For local configuration, resolve_local reads the documented environment fallbacks and therefore
needs environment.read. Sending chat_completions is a real HTTP effect and requires an explicitly
configured endpoint, timeout and credential handling. Do not print a live configuration record
containing secrets merely to prove that an adapter exists.
When adding a provider, preserve semantic message/event/result shapes at the public model boundary.
Keep provider-specific headers and endpoint paths in the adapter, document supported response
variants and test them against local fixtures before live traffic. A usage fixture does not verify
provider availability, streaming latency or authentication.
## usage
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | map | required | Already received OpenAI-compatible response record |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Public prompt_tokens/completion_tokens/total_tokens usage projection |
The `data` record is an observation rather than a request body. Missing counters follow the
public adapter convention; the example above contains two input tokens, three output tokens and
five total tokens. We return *[Read actual usage counters from the supplied response](openai.usage_from(data=`data`))*
without claiming to have measured a new model invocation.
## resolve_local
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Explicit local model override; None uses the adapter fallback |
| base_url | any | None | Explicit local API base URL; None uses the documented environment/default |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Actual Ollama configuration selected by the existing resolver |
The caller may supply `model`=None and `base_url`=None to use the shared local configuration
rules. Resolving the configuration does not launch a service or ask the model for a response.
We return *[Resolve local model fields with the existing adapter](ollama.resolve(model=`model`, base_url=`base_url`))*.
Treat the resulting configuration as runtime data and only execute a request after granting its effects.
+39 -19
View File
@@ -9,32 +9,41 @@ import:
---
## resolve
+ `model`=None
+ `base_url`=None
+ `api_key`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| model | any | None | Model resource or provider model identifier, as required by this operation |
| base_url | any | None | Provider API base URL |
| api_key | any | None | Provider credential from trusted runtime configuration |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`. |
Use `model`=None, `base_url`=None, `api_key`=None as the inputs for this operation.
Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `ollama`, model `llama3.2`.
1. `api_key`
**key = api_key**
We retain **key = api_key**.
2. *
**key = "ollama"**
We retain **key = "ollama"**.
1. `base_url`
**url = base_url**
We retain **url = base_url**.
2. *
**url = > sys.env_get name="OLLAMA_HOST"**
We retain **`url` = [Env get](sys.env_get(name="OLLAMA_HOST"))**.
1. not `url`
**url = "http://127.0.0.1:11434/v1"**
We retain **url = "http://127.0.0.1:11434/v1"**.
2. *
**_ = 1**
1. `model`
**mdl = model**
We retain **mdl = model**.
2. *
**mdl = > sys.env_get name="MARQDO_LLM_MODEL"**
We retain **`mdl` = [Env get](sys.env_get(name="MARQDO_LLM_MODEL"))**.
1. not `mdl`
**mdl = "llama3.2"**
We retain **mdl = "llama3.2"**.
2. *
**_ = 1**
@@ -44,14 +53,25 @@ Resolve Ollama handle fields: default host `http://127.0.0.1:11434/v1`, key `oll
|---------|---------|----------|-------|
| ollama | `key` | `url` | `mdl` |
*cfg*
Return *cfg*.
## chat_completions
+ `base_url`
+ `api_key`
+ `model`
+ `prompt`
+ `stream`=False
+ `echo`=False
*> openai.chat_completions base_url=`base_url` api_key=`api_key` model=`model` prompt=`prompt` stream=`stream` echo=`echo`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| base_url | any | required | Provider API base URL |
| api_key | any | required | Provider credential from trusted runtime configuration |
| model | any | required | Model resource or provider model identifier, as required by this operation |
| prompt | any | required | Prompt text or structured prompt expected by this adapter |
| stream | any | False | Whether to preserve streaming behavior or emit stream events |
| echo | any | False | Whether to print the documented incremental output |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions. |
Use `base_url`, `api_key`, `model`, `prompt`, `stream`=False, `echo`=False as the inputs for this operation.
Send the prepared chat request through this provider adapter and retain its usage, stream and failure conventions.
Return *[Chat completions](openai.chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, stream=`stream`, echo=`echo`))*.
+104 -73
View File
@@ -15,31 +15,40 @@ import:
---
## usage_from
+ `data`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map. |
Use `data` as the inputs for this operation.
Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped response map.
**u = > json.get value=`data` key="usage"**
We retain **`u` = [Read the usage field](json.get(value=`data`, key="usage"))**.
1. `u`
**pt = > json.get value=`u` key="prompt_tokens"**
**ct = > json.get value=`u` key="completion_tokens"**
**tt = > json.get value=`u` key="total_tokens"**
We retain **`pt` = [Read the prompt_tokens field](json.get(value=`u`, key="prompt_tokens"))**.
We retain **`ct` = [Read the completion_tokens field](json.get(value=`u`, key="completion_tokens"))**.
We retain **`tt` = [Read the total_tokens field](json.get(value=`u`, key="total_tokens"))**.
1. not `pt`
**pt = 0**
We retain **pt = 0**.
2. *
**_ = 1**
1. not `ct`
**ct = 0**
We retain **ct = 0**.
2. *
**_ = 1**
1. not `tt`
**tt = pt + ct**
We retain **tt = pt + ct**.
2. *
**_ = 1**
2. *
**pt = 0**
**ct = 0**
**tt = 0**
We retain **pt = 0**.
We retain **ct = 0**.
We retain **tt = 0**.
`usage` =
@@ -47,58 +56,77 @@ Extract `{prompt_tokens,completion_tokens,total_tokens}` from an OpenAI-shaped r
|---------------|-------------------|--------------|
| `pt` | `ct` | `tt` |
*usage*
Return *usage*.
## tool_calls_from
+ `data`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list). |
Use `data` as the inputs for this operation.
Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list).
**choices = > json.get value=`data` key="choices"**
We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**.
1. not `choices`
*> table.empty_list*
Return *[Empty list](table.empty_list())*.
2. *
**c0 = [1](access(choices, "1"))**
**msg = > json.get value=`c0` key="message"**
We retain **`c0` = [Read 1 field](access(`choices`, "1"))**.
We retain **`msg` = [Read the message field](json.get(value=`c0`, key="message"))**.
1. not `msg`
*> table.empty_list*
Return *[Empty list](table.empty_list())*.
2. *
**tc = > json.get value=`msg` key="tool_calls"**
We retain **`tc` = [Read the tool_calls field](json.get(value=`msg`, key="tool_calls"))**.
1. `tc`
*tc*
Return *tc*.
2. *
*> table.empty_list*
Return *[Empty list](table.empty_list())*.
## chat_completions
+ `base_url`
+ `api_key`
+ `model`
+ `prompt`=None
+ `messages`=None
+ `selection`=None
+ `strict_selection`=False
+ `auth_mode`=None
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
+ `suffix`=/chat/completions
+ `bearer`="Bearer "
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| base_url | any | required | Provider API base URL |
| api_key | any | required | Provider credential from trusted runtime configuration |
| model | any | required | Model resource or provider model identifier, as required by this operation |
| prompt | any | None | Prompt text or structured prompt expected by this adapter |
| messages | any | None | Ordered chat message records |
| selection | any | None | Explicit runtime/model selection |
| strict_selection | any | False | Whether an unresolved selection is an error |
| auth_mode | any | None | Authentication mode used by the provider adapter |
| stream | any | False | Whether to preserve streaming behavior or emit stream events |
| echo | any | False | Whether to print the documented incremental output |
| stream_kind | any | "delta" | Streaming event projection selected by the caller |
| suffix | any | "/chat/completions" | Provider endpoint suffix |
| bearer | any | "Bearer " | Bearer credential supplied by the configured provider |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | 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). Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin. |
Use `base_url`, `api_key`, `model`, `prompt`=None, `messages`=None, `selection`=None, `strict_selection`=False, `auth_mode`=None, `stream`=False, `echo`=False, `stream_kind`="delta", `suffix`="/chat/completions", `bearer`="Bearer " as the inputs for this operation.
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).
Pass either `messages=` (role/content list) or legacy `prompt=` (single user message). Optional `selection=` is a ModelSelectionV1 snapshot; `strict_selection=True` refuses env fallbacks inside the plugin.
`stream_kind` tags live EventBus frames: `delta` (answer tokens) or `plan` (parent protocol — UI process trail, not the bubble).
**p = > plugin.native_path name="llm"**
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="llm"))**.
1. `p`
> plugin.load path=`p`
*> llm_chat_completions base_url=`base_url` api_key=`api_key` model=`model` prompt=`prompt` messages=`messages` selection=`selection` strict_selection=`strict_selection` auth_mode=`auth_mode` stream=`stream` echo=`echo` stream_kind=`stream_kind` suffix=`suffix` bearer=`bearer`*
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
Return *[Llm chat completions](llm_chat_completions(base_url=`base_url`, api_key=`api_key`, model=`model`, prompt=`prompt`, messages=`messages`, selection=`selection`, strict_selection=`strict_selection`, auth_mode=`auth_mode`, stream=`stream`, echo=`echo`, stream_kind=`stream_kind`, suffix=`suffix`, bearer=`bearer`))*.
2. *
**url = base_url + suffix**
**auth = bearer + api_key**
**headers = > table.put in=None at="Authorization" value=`auth`**
We retain **url = base_url + suffix**.
We retain **auth = bearer + api_key**.
We retain **`headers` = [Set the Authorization field in the new record](table.put(in=None, at="Authorization", value=`auth`))**.
1. not `messages`
`messages` =
| @ | role | content |
@@ -114,19 +142,20 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes
| `model` | `messages` |
1. `stream`
**req = > table.put in=`req` at="stream" value=True**
We retain **`req` = [Set the stream field in the new record](table.put(in=`req`, at="stream", value=True))**.
`stream_opts` =
| include_usage |
|---------------|
| True |
**req = > table.put in=`req` at="stream_options" value=`stream_opts`**
**body = > json.stringify value=`req`**
**resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo`**
**st = > json.get value=`resp` key="status"**
We retain **`req` = [Set the stream_options field in the new record](table.put(in=`req`, at="stream_options", value=`stream_opts`))**.
We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**.
We retain **`resp` = [Http post sse](net.http_post_sse(url=`url`, body=`body`, headers=`headers`, echo=`echo`))**.
We retain **`st` = [Read the status field](json.get(value=`resp`, key="status"))**.
1. `st` == 200
**evs = > json.get value=`resp` key="events"**
We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**.
`pack` =
@@ -134,45 +163,46 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes
|--------|--------|
| stop | `evs` |
*pack*
Return *pack*.
2. *
Soft transport / HTTP failure — structured pack, never abort the VM.
**msg = "HTTP " + `st`**
**evs = > json.get value=`resp` key="events"**
We retain **msg = "HTTP " + `st`**.
We retain **`evs` = [Read the events field](json.get(value=`resp`, key="events"))**.
1. `evs`
**e0 = > at value=`evs` index=0**
**m2 = > json.get value=`e0` key="message"**
We retain **`e0` = [At](at(value=`evs`, index=0))**.
We retain **`m2` = [Read the message field](json.get(value=`e0`, key="message"))**.
1. `m2`
**msg = `m2`**
We retain **msg = `m2`**.
`pack` =
| finish | text | error | events |
|--------|------|-------|--------|
| error | "" | `msg` | `evs` |
*pack*
Return *pack*.
2. *
**body = > json.stringify value=`req`**
**resp = > net.http_post url=`url` body=`body` headers=`headers`**
**st = > json.get value=`resp` key="status"**
We retain **`body` = [Encode the structured value as JSON text](json.stringify(value=`req`))**.
We retain **`resp` = [Http post](net.http_post(url=`url`, body=`body`, headers=`headers`))**.
We retain **`st` = [Read the status field](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"**
We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**.
We retain **`data` = [Parse the JSON transport text](json.parse(text=`raw`))**.
We retain **`choices` = [Read the choices field](json.get(value=`data`, key="choices"))**.
We retain **`choice0` = [At](at(value=`choices`, index=0))**.
We retain **`msg` = [Read the message field](json.get(value=`choice0`, key="message"))**.
We retain **`text` = [Read the content field](json.get(value=`msg`, key="content"))**.
1. not `text`
**text = ""**
We retain **text = ""**.
2. *
**_ = 1**
**usage = > usage_from data=`data`**
**fr = > json.get value=`choice0` key="finish_reason"**
We retain **`usage` = [Usage from](usage_from(data=`data`))**.
We retain **`fr` = [Read the finish_reason field](json.get(value=`choice0`, key="finish_reason"))**.
1. not `fr`
**fr = "stop"**
We retain **fr = "stop"**.
2. *
**_ = 1**
**tc = > tool_calls_from data=`data`**
We retain **`tc` = [Tool calls from](tool_calls_from(data=`data`))**.
`pack` =
@@ -180,20 +210,21 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes
|--------|------|-------|------------|
| `fr` | `text` | `usage` | `tc` |
*pack*
Return *pack*.
2. *
Soft transport / HTTP failure — structured pack, never abort the VM.
**raw = > json.get value=`resp` key="body"**
**msg = "HTTP " + `st`**
We retain **`raw` = [Read the body field](json.get(value=`resp`, key="body"))**.
We retain **msg = "HTTP " + `st`**.
1. `raw`
**msg = `msg` + ": " + `raw`**
We retain **msg = `msg` + ": " + `raw`**.
`usage0` =
| prompt_tokens | completion_tokens | total_tokens |
|---------------|-------------------|--------------|
| 0 | 0 | 0 |
**empty_tc = > table.empty_list**
We retain **`empty_tc` = [Empty list](table.empty_list())**.
`pack` =
@@ -201,4 +232,4 @@ Pass either `messages=` (role/content list) or legacy `prompt=` (single user mes
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
Return *pack*.
+21 -3
View File
@@ -6,21 +6,39 @@ description: >
Readable authority for agent.step_route; do not invent a second dialect.
---
# Step class → backend
Step class to backend.
Authors and `agent.step_route` read this table. Backends match Adaptive Routing:
`marqdo` | `small-llm` | `llm` | `auto`.
## routes
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Return the same readable route table used by the agent policy reader. |
Return the same readable route table used by the agent policy reader.
Each column is a list with the same row order. Lookup and sandbox execution prefer Marqdo, patch work prefers the small model, and network-oriented work uses the model route. The default row leaves the final choice to the existing router. Returning these values does not load or invoke a backend.
**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` |
| sandbox_run | marqdo | "CoW trial of .mq.md" |
| net | llm | Needs network / toolful turn |
| default | auto | Cascade policy → kb → small-llm |
Return *routes*.
# main
*routes*
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | The entry returns the policy data without creating a second routing dialect. |
The entry returns the policy data without creating a second routing dialect.
Return *[Routes](routes())*.
+198 -71
View File
@@ -15,17 +15,34 @@ 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.
CoW trial operations belong here; attaching a sandbox profile to another result does not isolate execution. [The AI entry](index.mq.md) explains the relation to model and agent resources. A trial produces inspectable changes; promotion is a separate existing operation with its own checks. Keep cancellation, failed execution and explicit promotion visible, and never equate a generated source file with a committed successful outcome.
## ensure_plugin
**p = plugin.native_path name="agent"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the required native ABI plugin; missing binaries report a diagnostic message and stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="agent"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](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
We **[Print the prepared message](print(text="ext/ai/sandbox: native agent plugin not found (build marqdo_plugin_agent or marqdo ext add agent)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
## profile
+ `name`=default
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | any | "default" | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`. Catalog (documentation + authority): |
Use `name`="default" as the inputs for this operation.
Named caps row as a map table (`name`, `fs_write`, `exec`, `net`, `plugin`). Unknown names → `default`.
@@ -50,139 +67,249 @@ Catalog (documentation + authority):
|------|----------|------|-----|--------|
| default | true | false | false | false |
*row*
Return *row*.
## open_native
+ `root`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| root | any | None | Explicit root directory for discovery or isolated execution |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade. |
Use `root`=None as the inputs for this operation.
Native CoW open (plugin ABI italic return). Prefer `## open` for the profile-aware facade.
> ensure_plugin
We **[Load the native plugin required by this operation](ensure_plugin())**.
1. `root`
*> sandbox_open root=`root`*
Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open(root=`root`))*.
2. *
*> sandbox_open*
Return *[Native CoW open (plugin ABI italic return). Prefer ## open for the profile-aware facade.](sandbox_open())*.
## open
+ `root`=None
+ `profile`=default
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| root | any | None | Explicit root directory for discovery or isolated execution |
| profile | any | "default" | Capability profile selected for the trial |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Open a CoW session. Optional `root=` (directory). Default: entry file directory. |
Use `root`=None, `profile`="default" as the inputs for this operation.
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*
We retain **`sess` = [Open native](open_native(root=`root`))**.
We retain **`prof` = [Profile](profile(name=`profile`))**.
We retain **`sess` = [Set the profile field in the new record](table.put(in=`sess`, at="profile", value=`prof`))**.
Return *sess*.
## write
+ `id`
+ `path`
+ `text`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects |
| text | any | required | Text supplied to the transformation or adapter |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Write text into the session upper layer (host tree unchanged until `commit`). |
Use `id`, `path`, `text` as the inputs for this operation.
Write text into the session upper layer (host tree unchanged until `commit`).
> ensure_plugin
*> sandbox_write id=`id` path=`path` text=`text`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Write text into the session upper layer (host tree unchanged until commit).](sandbox_write(id=`id`, path=`path`, text=`text`))*.
## read
+ `id`
+ `path`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Read through CoW (upper, else lower; whiteout misses). |
Use `id`, `path` as the inputs for this operation.
Read through CoW (upper, else lower; whiteout misses).
> ensure_plugin
*> sandbox_read id=`id` path=`path`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Read through CoW (upper, else lower; whiteout misses).](sandbox_read(id=`id`, path=`path`))*.
## remove
+ `id`
+ `path`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Logical delete (whiteout). |
Use `id`, `path` as the inputs for this operation.
Logical delete (whiteout).
> ensure_plugin
*> sandbox_remove id=`id` path=`path`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Logical delete (whiteout).](sandbox_remove(id=`id`, path=`path`))*.
## diff
+ `id`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | List of `{ path, kind }` pending changes (`write` &#124; `remove`). |
Use `id` as the inputs for this operation.
List of `{ path, kind }` pending changes (`write` | `remove`).
> ensure_plugin
*> sandbox_diff id=`id`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[List of { path, kind } pending changes (write | remove).](sandbox_diff(id=`id`))*.
## commit
+ `id`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Apply upper / whiteout to the real workspace root. |
Use `id` as the inputs for this operation.
Apply upper / whiteout to the real workspace root.
> ensure_plugin
*> sandbox_commit id=`id`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Apply upper / whiteout to the real workspace root.](sandbox_commit(id=`id`))*.
## discard
+ `id`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Drop the session without writing the host tree. |
Use `id` as the inputs for this operation.
Drop the session without writing the host tree.
> ensure_plugin
*> sandbox_discard id=`id`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Drop the session without writing the host tree.](sandbox_discard(id=`id`))*.
## run
+ `id`
+ `source`=None
+ `path`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| source | any | None | Source text inspected or prepared by this operation |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW). Pass `source=` or `path=` (relative to session root). |
Use `id`, `source`=None, `path`=None as the inputs for this operation.
Run Marqdo under sandbox caps (`exec` / `net` / `plugin` off; fs via CoW).
Pass `source=` or `path=` (relative to session root).
> ensure_plugin
We **[Load the native plugin required by this operation](ensure_plugin())**.
1. `source`
*> sandbox_run id=`id` source=`source`*
Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, source=`source`))*.
2. `path`
*> sandbox_run id=`id` path=`path`*
Return *[Run Marqdo under sandbox caps (exec / net / plugin off; fs via CoW). Pass source= or path= (relative to session root).](sandbox_run(id=`id`, path=`path`))*.
3. *
> print text=ext/ai/sandbox.run: need source= or path=
> sys.exit code=1
We **[Print the prepared message](print(text="ext/ai/sandbox.run: need", source="or", path=""))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
## inspect_native
+ `id`
> ensure_plugin
*> sandbox_inspect id=`id`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Inspect an existing native CoW session without promoting its writes. |
Use `id` as the inputs for this operation.
Inspect an existing native CoW session without promoting its writes.
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Inspect an existing native CoW session without promoting its writes.](sandbox_inspect(id=`id`))*.
## inspect
+ `id`
+ `profile`=default
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| profile | any | "default" | Capability profile selected for the trial |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Native caps / change counts, plus the GFM `## profile` row under key `profile`. |
Use `id`, `profile`="default" as the inputs for this operation.
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*
We retain **`raw` = [Inspect native](inspect_native(id=`id`))**.
We retain **`prof` = [Profile](profile(name=`profile`))**.
We retain **`out` = [Set the profile field in the new record](table.put(in=`raw`, at="profile", value=`prof`))**.
Return *out*.
## report
+ `id`
+ `path`=sandbox-diff.md
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| path | any | "sandbox-diff.md" | Explicit filesystem path; honor the documented filesystem root and operation effects |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report file, not a UI rewrite). |
Use `id`, `path`="sandbox-diff.md" as the inputs for this operation.
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"**
We retain **`pending` = [Diff](diff(id=`id`))**.
We retain **`n` = [Len](len(value=`pending`))**.
We retain **body = "# Sandbox diff report\n\nPending changes: "**.
We retain **body = body + n**.
We retain **body = body + "\n\n| path | kind |\n|------|------|\n"**.
- [row](遍历 pending 为 row)
**p = [path](access(row, "path"))**
**k = [kind](access(row, "kind"))**
**body = body + "| "**
**body = body + p**
**body = body + " | "**
**body = body + k**
**body = body + " |\n"**
> fs.write_text path=`path` text=`body`
We retain **`p` = [Read path field](access(`row`, "path"))**.
We retain **`k` = [Read kind field](access(`row`, "kind"))**.
We retain **body = body + "| "**.
We retain **body = body + p**.
We retain **body = body + " | "**.
We retain **body = body + k**.
We retain **body = body + " |\n"**.
We **[Write the prepared text to the selected file](fs.write_text(path=`path`, text=`body`))**.
**out = **
@@ -190,4 +317,4 @@ O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report
|------|-------|
| `path` | `n` |
*out*
Return *out*.
+342 -147
View File
@@ -5,6 +5,7 @@ description: >-
Marqdo 大模型智能原语 — 提问 / 流式 / 收集 / 命名句柄。
OpenAI 兼容与 Ollama HTTP 藏在语义面之后。
导入:
table: lib/table.mq.md
系统: lib/系统.mq.md
json: lib/json.mq.md
文件: lib/文件.mq.md
@@ -12,64 +13,90 @@ description: >-
openai: ext/ai/llm/openai.mq.md
---
## 加载环境
+ `路径`=None
本文件是中文模型资源门面;从[中文入口](索引.mq.md)可以先运行无需联网的事件收集示例。提供方请求实现位于 llm 子目录,智能体编排位于智能体文件。创建资源只解析配置;真实请求还需插件、服务和授权。修改时同时核对英文模型面、语义事件、用量字段与传输失败,不把空文本当作可靠的成功信号。
*> 系统.加载环境 路径=`路径`*
## 加载环境
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 授权根目录内的文件路径 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。 |
这里使用`路径`=None。
读取指定 dotenv 文件且保留已有环境变量;它不发送模型请求。
完成后返回*[调用 加载环境](系统.加载环境(路径=`路径`))*。
## 收集
+ `事件`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 事件 | any | 必填 | 按顺序排列的流事件记录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | Collapse stream events to text. Supports semantic `delta`/`done.result` and native-plugin raw frames (`type=data` + OpenAI chunk JSON). |
这里使用`事件`。
Collapse stream events to text. Supports semantic `delta`/`done.result` and
native-plugin raw frames (`type=data` + OpenAI chunk JSON).
**answer = ""**
例如先收到两个 delta 再收到 done 时,以最后非空 result 为准;只收到无内容事件则返回空文本。按事件顺序处理文本:delta 与 text 的 text 字段追加到当前回答;done 中非空的 result 覆盖累积文本;error 中非空的 message 也成为当前文本。因此返回的是收集文本,不是独立的成功状态。调用方若需区分失败,应同时检查原始事件,不能把非空文本当成请求成功。
兼容的 data 事件承载提供方 JSON。结束标记 [DONE] 不作为正文;普通数据从首条 choice 的 delta.content 或 message.content 读取。缺失内容不会凭空产生片段,JSON 解码失败仍遵循解析库的诊断。这里不排序、不重试,也不发送模型请求;输入顺序决定最终文字,空事件序列得到空字符串。
得到**answer = ""**。
- [ev](遍历 事件 为 ev)
**t = [type](access(ev, "type"))**
得到**`t` = [读取 type 字段](access(`ev`, "type"))**。
1. `t` == "done"
**done_r = [result](access(ev, "result"))**
得到**`done_r` = [读取 result 字段](access(`ev`, "result"))**。
1. `done_r`
**answer = `done_r`**
得到**answer = `done_r`**。
2. *
**_ = 1**
2. `t` == "error"
**em = [message](access(ev, "message"))**
得到**`em` = [读取 message 字段](access(`ev`, "message"))**。
1. `em`
**answer = `em`**
得到**answer = `em`**。
2. *
**_ = 1**
3. `t` == "delta"
4. `t` == "text"
**chunk = [text](access(ev, "text"))**
得到**`chunk` = [读取 text 字段](access(`ev`, "text"))**。
1. `chunk`
**answer = answer + chunk**
得到**answer = answer + chunk**。
2. *
**_ = 1**
5. `t` == "data"
**raw = [data](access(ev, "data"))**
得到**`raw` = [读取 data 字段](access(`ev`, "data"))**。
1. `raw`
1. `raw` == "[DONE]"
**_ = 1**
2. *
**parsed = > json.parse text=`raw`**
得到**`parsed` = [解析 JSON 传输文本](json.parse(text=`raw`))**。
1. `parsed`
**choices = [choices](access(parsed, "choices"))**
得到**`choices` = [读取 choices 字段](access(`parsed`, "choices"))**。
1. `choices`
**c0 = [1](access(choices, "1"))**
**delta = [delta](access(c0, "delta"))**
得到**`c0` = [读取 1 字段](access(`choices`, "1"))**。
得到**`delta` = [读取 delta 字段](access(`c0`, "delta"))**。
1. `delta`
**piece = [content](access(delta, "content"))**
得到**`piece` = [读取 content 字段](access(`delta`, "content"))**。
1. `piece`
**answer = answer + piece**
得到**answer = answer + piece**。
2. *
**_ = 1**
2. *
**msg = [message](access(c0, "message"))**
得到**`msg` = [读取 message 字段](access(`c0`, "message"))**。
1. `msg`
**piece = [content](access(msg, "content"))**
得到**`piece` = [读取 content 字段](access(`msg`, "content"))**。
1. `piece`
**answer = answer + piece**
得到**answer = answer + piece**。
2. *
**_ = 1**
2. *
@@ -84,180 +111,291 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON).
**_ = 1**
1. not `answer`
**answer = ""**
*answer*
得到**answer = ""**。
完成后返回*answer*。
## 流式结果
+ `事件`
*> 收集 事件=`事件`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 事件 | any | 必填 | 按顺序排列的流事件记录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将流事件交给同源收集器,返回最终回答文本。 |
这里使用`事件`。
将流事件交给同源收集器,返回最终回答文本。
完成后返回*[调用 收集](收集(事件=`事件`))*。
## 用量
+ `数据`
*> openai.usage_from data=`数据`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 数据 | any | 必填 | 交给本操作处理的结构化数据 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 从提供方响应中提取 token 用量,缺失计数采用公开实现约定。 |
这里使用`数据`。
从提供方响应中提取 token 用量,缺失计数采用公开实现约定。
完成后返回*[调用 usage from](openai.usage_from(data=`数据`))*。
## 创建
+ `模型`=None
+ `基址`=None
+ `密钥`=None
+ `后端`=openai-compatible
+ `名`=None
**h = > 大模型 模型=`模型` 基址=`基址` 密钥=`密钥` 后端=`后端` 名=`名`**
*h*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 模型 | any | None | 已配置的模型资源或模型标识 |
| 基址 | any | None | 提供方 API 基址 |
| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 |
| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 |
| 名 | any | None | 本操作注册或查找的名称 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。 |
这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。
按模型、基址和鉴权配置创建可复用的大模型资源;此步骤不请求回答。
得到**`h` = [调用 大模型](大模型(模型=`模型`, 基址=`基址`, 密钥=`密钥`, 后端=`后端`, 名=`名`))**。
完成后返回*h*。
## 快速
+ `模型`=None
+ `基址`=None
+ `密钥`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 模型 | any | None | 已配置的模型资源或模型标识 |
| 基址 | any | None | 提供方 API 基址 |
| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 |
这里使用`模型`=None、`基址`=None、`密钥`=None。
1. `模型`
**mdl = 模型**
得到**mdl = 模型**。
2. *
**mdl = > 系统.取环境 名="MARQDO_LLM_FAST_MODEL"**
得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_FAST_MODEL"))**。
*> 创建 模型=`mdl` 基址=`基址` 密钥=`密钥` 名="fast" 后端="openai-compatible"*
完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="fast", 后端="openai-compatible"))*。
## 推理
+ `模型`=None
+ `基址`=None
+ `密钥`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 模型 | any | None | 已配置的模型资源或模型标识 |
| 基址 | any | None | 提供方 API 基址 |
| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 创建,保留同源能力的返回值和失败语义。 |
这里使用`模型`=None、`基址`=None、`密钥`=None。
1. `模型`
**mdl = 模型**
得到**mdl = 模型**。
2. *
**mdl = > 系统.取环境 名="MARQDO_LLM_REASONING_MODEL"**
得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_REASONING_MODEL"))**。
*> 创建 模型=`mdl` 基址=`基址` 密钥=`密钥` 名="reasoning" 后端="openai-compatible"*
完成后返回*[调用 创建](创建(模型=`mdl`, 基址=`基址`, 密钥=`密钥`, 名="reasoning", 后端="openai-compatible"))*。
## 提示正文
+ `源`
**sw = > 文本.开头是 内容=`源` 前缀="---"**
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 源 | any | 必填 | 提示正文或源码来源 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 从指定文本构造提示正文,保留输入内容而不请求模型。 |
这里使用`源`。
从指定文本构造提示正文,保留输入内容而不请求模型。
这里只识别源文本开头的前置元数据,且仅对声明为 prompt 或提示的文档提取正文。普通 Markdown、没有结束分隔线的文本和其他类型文档原样保留。正文只取当前分隔实现得到的首段并去掉两端空白,不承担通用 YAML 解析或提示模板插值;需要完整文件时使用文件库读取。
得到**`sw` = [调用 开头是](文本.开头是(内容=`源`, 前缀="---"))**。
1. 非 `sw`
*源*
完成后返回*源*。
2. *
**parts = > split value=`源` sep="\n---\n"**
**n = > len value=`parts`**
得到**`parts` = [调用 split](split(value=`源`, sep="\n---\n"))**。
得到**`n` = [调用 len](len(value=`parts`))**。
1. `n` < 2
*源*
完成后返回*源*。
2. *
**fm = > at value=`parts` index=0**
**is_p = > 文本.包含 内容=`fm` 子串="type: prompt"**
得到**`fm` = [调用 at](at(value=`parts`, index=0))**。
得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="type: prompt"))**。
1. 非 `is_p`
**is_p = > 文本.包含 内容=`fm` 子串="类型: 提示"**
得到**`is_p` = [调用 包含](文本.包含(内容=`fm`, 子串="类型: 提示"))**。
2. *
**_ = 1**
1. `is_p`
**body = > at value=`parts` index=1**
*> 文本.去空白 s=`body`*
得到**`body` = [调用 at](at(value=`parts`, index=1))**。
完成后返回*[调用 去空白](文本.去空白(s=`body`))*。
2. *
*源*
完成后返回*源*。
## 加载提示
+ `路径`
**raw = > 文件.读文本 路径=`路径`**
*> 提示正文 源=`raw`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | 必填 | 授权根目录内的文件路径 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 从指定文件加载提示正文;文件访问仍受宿主文件权限限制。 |
这里使用`路径`。
从指定文件加载提示正文;文件访问仍受宿主文件权限限制。
得到**`raw` = [读取指定文件的 UTF-8 正文](文件.读文本(路径=`路径`))**。
完成后返回*[调用 提示正文](提示正文(源=`raw`))*。
## 提示
+ `路径`=None
+ `文本`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 授权根目录内的文件路径 |
| 文本 | any | None | 本操作接收的文本 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 提示正文,保留同源能力的返回值和失败语义。 |
这里使用`路径`=None、`文本`=None。
1. `路径`
*> 加载提示 路径=`路径`*
完成后返回*[调用 加载提示](加载提示(路径=`路径`))*。
2. `文本`
*> 提示正文 源=`文本`*
完成后返回*[调用 提示正文](提示正文(源=`文本`))*。
3. *
> 打印 内容=ext/ai/大模型.提示: 请传 路径= 或 文本=
> 系统.退出 码=1
这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提示: 请传", 路径="或", 文本=""))**。
这里**[调用 退出](系统.退出(码=1))**。
## 提问
+ `提示`=None
+ `路径`=None
+ `模型`=None
+ `基址`=None
+ `密钥`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | None | 提供给模型的提示内容 |
| 路径 | any | None | 授权根目录内的文件路径 |
| 模型 | any | None | 已配置的模型资源或模型标识 |
| 基址 | any | None | 提供方 API 基址 |
| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 |
| p | any | 必填 | Prompt value passed to the selected model |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 |
这里使用`提示`=None、`路径`=None、`模型`=None、`基址`=None、`密钥`=None、`p`。
1. `路径`
**p = > 加载提示 路径=`路径`**
得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。
2. `提示`
**p = 提示**
得到**p = 提示**。
3. *
> 打印 内容=ext/ai/大模型.提问: 请传 提示= 或 路径=
> 系统.退出 码=1
这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型.提问: 请传", 提示="或", 路径=""))**。
这里**[调用 退出](系统.退出(码=1))**。
**m = > 创建 模型=`模型` 基址=`基址` 密钥=`密钥`**
**r = > m.提问 提示=`p`**
*[text](access(r, "text"))*
得到**`m` = [调用 创建](创建(模型=`模型`, 基址=`基址`, 密钥=`密钥`))**。
得到**`r` = [调用 提问](m.提问(提示=`p`))**。
完成后返回*[text](access(r, "text"))*。
# 大模型
+ `模型`=None
+ `基址`=None
+ `密钥`=None
+ `后端`=openai-compatible
+ `名`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 模型 | any | None | 已配置的模型资源或模型标识 |
| 基址 | any | None | 提供方 API 基址 |
| 密钥 | any | None | 可信运行配置提供的凭据,不应写入日志 |
| 后端 | any | "openai-compatible" | 明确选择的执行或模型后端 |
| 名 | any | None | 本操作注册或查找的名称 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 |
这里使用`模型`=None、`基址`=None、`密钥`=None、`后端`="openai-compatible"、`名`=None。
1. `密钥`
**key = 密钥**
构造器只整理连接配置并返回资源记录,不在此请求回答。显式传入的密钥优先,其后依次读取 OPENAI_API_KEY 与 MARQDO_LLM_API_KEY。兼容后端没有密钥会输出原因并以非零状态结束;本地 ollama 使用占位凭据以维持相同资源结构。记录包含实际凭据,应由调用方保管,避免直接打印整个句柄。
基址的选择同样保留显式值。ollama 未配置时使用本机兼容接口;其他后端依次尝试 OPENAI_BASE_URL、MARQDO_LLM_BASE_URL,最后采用公开默认地址。模型名依次来自显式值、OPENAI_MODEL、MARQDO_LLM_MODEL,最后按后端选用默认模型。默认模型名称只是现有运行约定,不保证提供方已开通、服务器已安装或网络可达。
返回记录保存后续请求所需的模型、后端、请求后缀、认证前缀和可选名称。实例方法从这个记录读取配置;改变环境不会自动重建已有句柄。需要切换配置时重新构造,不要把资源创建成功等同于鉴权或连通性验证。真实请求还要准备对应原生插件与运行授权;离线读取配置和真实网络调用是两个阶段。
例如在没有外部服务的离线配置检查中,可以显式选择 ollama、提供模型名与本地基址,只核对返回字段而不调用提问。在线验收则必须再检查真实请求的结束原因和用量。删除或覆盖环境配置前,也应考虑已有句柄仍保存旧凭据;本构造器不会主动清理其他资源或替调用方撤销密钥。
得到**key = 密钥**。
2. *
**key = > 系统.取环境 名="OPENAI_API_KEY"**
得到**`key` = [调用 取环境](系统.取环境(名="OPENAI_API_KEY"))**。
1. 非 `key`
**key = > 系统.取环境 名="MARQDO_LLM_API_KEY"**
得到**`key` = [调用 取环境](系统.取环境(名="MARQDO_LLM_API_KEY"))**。
2. *
**_ = 1**
1. `后端` == ollama
1. 非 `key`
**key = "ollama"**
得到**key = "ollama"**。
2. *
**_ = 1**
2. 非 `key`
> 打印 内容=ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY
> 系统.退出 码=1
这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY"))**。
这里**[调用 退出](系统.退出(码=1))**。
3. *
**_ = 1**
1. `基址`
**url = 基址**
得到**url = 基址**。
2. `后端` == ollama
**url = > 系统.取环境 名="OLLAMA_HOST"**
得到**`url` = [调用 取环境](系统.取环境(名="OLLAMA_HOST"))**。
1. 非 `url`
**url = "http://127.0.0.1:11434/v1"**
得到**url = "http://127.0.0.1:11434/v1"**。
2. *
**_ = 1**
3. *
**url = > 系统.取环境 名="OPENAI_BASE_URL"**
得到**`url` = [调用 取环境](系统.取环境(名="OPENAI_BASE_URL"))**。
1. 非 `url`
**url = > 系统.取环境 名="MARQDO_LLM_BASE_URL"**
得到**`url` = [调用 取环境](系统.取环境(名="MARQDO_LLM_BASE_URL"))**。
2. *
**_ = 1**
1. 非 `url`
**url = "https://api.openai.com/v1"**
得到**url = "https://api.openai.com/v1"**。
2. *
**_ = 1**
1. `模型`
**mdl = 模型**
得到**mdl = 模型**。
2. *
**mdl = > 系统.取环境 名="OPENAI_MODEL"**
得到**`mdl` = [调用 取环境](系统.取环境(名="OPENAI_MODEL"))**。
1. 非 `mdl`
**mdl = > 系统.取环境 名="MARQDO_LLM_MODEL"**
得到**`mdl` = [调用 取环境](系统.取环境(名="MARQDO_LLM_MODEL"))**。
2. *
**_ = 1**
1. 非 `mdl`
1. `后端` == ollama
**mdl = "llama3.2"**
得到**mdl = "llama3.2"**。
2. *
**mdl = "gpt-4o-mini"**
得到**mdl = "gpt-4o-mini"**。
2. *
**_ = 1**
1. `名`
**nm = 名**
得到**nm = 名**。
2. *
**nm = None**
得到**nm = None**。
`h` =
@@ -265,36 +403,52 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON).
|-------|---------|---------|----------|-------|--------|--------|------|
| 大模型 | `后端` | `key` | `url` | `mdl` | /chat/completions | "Bearer " | `nm` |
*h*
完成后返回*h*。
## 提问
+ `提示`=None
+ `路径`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | None | 提供给模型的提示内容 |
| 路径 | any | None | 授权根目录内的文件路径 |
| p | any | 必填 | Prompt value passed to the selected model |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 |
这里使用`提示`=None、`路径`=None、`p`。
1. `路径`
**p = > 加载提示 路径=`路径`**
2. `提示`
**p = 提示**
3. *
> 打印 内容=ext/ai/大模型: 提问需要 提示= 或 路径=
> 系统.退出 码=1
路径与直接提示同时存在时,先从路径加载提示;否则使用非空提示。两者都缺失时明确结束运行。当前接口还保留历史推断得到的 p 输入,表中如实列出其签名;本方法实际按上述分支重新设置请求正文,调用方不应把这个内部兼容参数当成另一种提示来源。
**pack = > 自.完整结果 提示=`p` 流式=False 打印增量=False**
**text = > json.get value=`pack` key="text"**
**usage = > json.get value=`pack` key="usage"**
**finish = > json.get value=`pack` key="finish"**
**tc = > json.get value=`pack` key="tool_calls"**
完整结果提供文本、结束原因、工具调用与用量。这里将它们整理为含模型与后端的记录;工具调用缺失时给出空列表。tokens 取 usage 中的 total_tokens,不能由回答字符数推算。llm_calls 是该接口的调用计数字段,并非计费凭据或独立的成功证明。网络失败应按完整结果的 finish 和相关诊断处理,不能只看 text 是否非空。
例如消费返回值时,先确认 finish,再取 text 展示;若 tool_calls 非空,则由上层明确决定是否进入受授权的工具流程。本方法只整理模型响应,不会看到工具请求就自动执行,也不会为调用方写入会话记录或文件。
得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。
2. `提示`
得到**p = 提示**。
3. *
这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 提问需要", 提示="或", 路径=""))**。
这里**[调用 退出](系统.退出(码=1))**。
得到**`pack` = [调用 完整结果](自.完整结果(提示=`p`, 流式=False, 打印增量=False))**。
得到**`text` = [读取 text 字段](json.get(value=`pack`, key="text"))**。
得到**`usage` = [读取 usage 字段](json.get(value=`pack`, key="usage"))**。
得到**`finish` = [读取 finish 字段](json.get(value=`pack`, key="finish"))**。
得到**`tc` = [读取 tool_calls 字段](json.get(value=`pack`, key="tool_calls"))**。
1. not `tc`
**tc = > json.parse text=[]**
没有工具调用时,使用**tc = [创建空工具调用列表](table.empty_list())**,避免将缺失值误作一条调用。
2. *
**_ = 1**
表单元格会遮蔽 `自` / 列名,先取出字段再组结果表。
**mdl = [model](access(自, "model"))**
**b = [backend](access(自, "backend"))**
**nm = [name](access(自, "name"))**
**tt = [total_tokens](access(usage, "total_tokens"))**
得到**`mdl` = [读取 model 字段](access(`自`, "model"))**。
得到**`b` = [读取 backend 字段](access(`自`, "backend"))**。
得到**`nm` = [读取 name 字段](access(`自`, "name"))**。
得到**`tt` = [读取 total_tokens 字段](access(`usage`, "total_tokens"))**。
`result` =
@@ -302,45 +456,86 @@ native-plugin raw frames (`type=data` + OpenAI chunk JSON).
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
*result*
完成后返回*result*。
## 流式
+ `提示`=None
+ `路径`=None
+ `打印增量`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | None | 提供给模型的提示内容 |
| 路径 | any | None | 授权根目录内的文件路径 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| p | any | 必填 | Prompt value passed to the selected model |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 运行,保留同源能力的返回值和失败语义。 |
这里使用`提示`=None、`路径`=None、`打印增量`=False、`p`。
1. `路径`
**p = > 加载提示 路径=`路径`**
得到**`p` = [调用 加载提示](加载提示(路径=`路径`))**。
2. `提示`
**p = 提示**
得到**p = 提示**。
3. *
> 打印 内容=ext/ai/大模型: 流式需要 提示= 或 路径=
> 系统.退出 码=1
这里**[输出本步已准备的消息](打印(内容="ext/ai/大模型: 流式需要", 提示="或", 路径=""))**。
这里**[调用 退出](系统.退出(码=1))**。
*> 自.运行 提示=`p` 流式=True 打印增量=`打印增量`*
完成后返回*[调用 运行](自.运行(提示=`p`, 流式=True, 打印增量=`打印增量`))*。
## 完整结果
+ `提示`
+ `流式`=False
+ `打印增量`=False
*> openai.chat_completions base_url=[base_url](access(自, "base_url")) api_key=[api_key](access(自, "api_key")) model=[model](access(自, "model")) prompt=`提示` stream=`流式` echo=`打印增量` suffix=[suffix](access(自, "suffix")) bearer=[bearer](access(自, "bearer"))*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | 必填 | 提供给模型的提示内容 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 使用此大模型资源请求完整响应,保留文本、用量和失败信息。 |
这里使用`提示`、`流式`=False、`打印增量`=False。
使用此大模型资源请求完整响应,保留文本、用量和失败信息。
完成后返回*[调用 chat completions](openai.chat_completions(base_url=[base_url](access(`自`, "base_url")), api_key=[api_key](access(`自`, "api_key")), model=[model](access(`自`, "model")), prompt=`提示`, stream=`流式`, echo=`打印增量`, suffix=[suffix](access(`自`, "suffix")), bearer=[bearer](access(`自`, "bearer"))))*。
## 运行
+ `提示`
+ `流式`=False
+ `打印增量`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | 必填 | 提供给模型的提示内容 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 access,保留同源能力的返回值和失败语义。 |
这里使用`提示`、`流式`=False、`打印增量`=False。
1. `流式`
**pack = > 自.完整结果 提示=`提示` 流式=True 打印增量=`打印增量`**
*[events](access(pack, "events"))*
得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=True, 打印增量=`打印增量`))**。
完成后返回*[events](access(pack, "events"))*。
2. *
**pack = > 自.完整结果 提示=`提示` 流式=False 打印增量=`打印增量`**
*[text](access(pack, "text"))*
得到**`pack` = [调用 完整结果](自.完整结果(提示=`提示`, 流式=False, 打印增量=`打印增量`))**。
完成后返回*[text](access(pack, "text"))*。
## 聊天
+ `提示`
+ `流式`=False
+ `打印增量`=False
*> 自.运行 提示=`提示` 流式=`流式` 打印增量=`打印增量`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 提示 | any | 必填 | 提供给模型的提示内容 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。 |
这里使用`提示`、`流式`=False、`打印增量`=False。
使用此资源执行带历史消息的聊天请求,并保留公开实现的返回形态。
完成后返回*[调用 运行](自.运行(提示=`提示`, 流式=`流式`, 打印增量=`打印增量`))*。
+360 -210
View File
@@ -14,82 +14,127 @@ description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编
插件: lib/插件.mq.md
---
本文件保留中文智能体的模型运行接口与工具调用流程。[中文入口](索引.mq.md)说明模型、编排与试跑的职责边界。内部函数的存在不代表它已进入模型白名单;工具请求必须由作者明确授权。开发时用离线模型替身核对历史、调用点、结果与写回,再测试真实传输。需要隔离执行时使用实际试跑入口,不能仅向结果附加配置记录。
## 构建单步上下文
+ `智能体`
+ `任务`
+ `源码深度`=default
+ `技能深度`=default
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 智能体 | any | 必填 | 本库创建的智能体配置或接收者 |
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 源码深度 | any | "default" | 源码上下文读取深度,默认遵循预算 |
| 技能深度 | any | "default" | 技能上下文读取深度,默认遵循预算 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。 编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source&#124;skill` 加深再答或 `调用:`。 实现委托 `agent.build_step_context`(与英文版同源)。 |
这里使用`智能体`、`任务`、`源码深度`="default"、`技能深度`="default"。
组装可读提示:站立提示、任务、*调用位置*、工具、*预算*源码 + Skill,以及人可见的行动约定。
编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。
实现委托 `agent.build_step_context`(与英文版同源)。
*> agent.build_step_context agent=`智能体` task=`任务` source_depth=`源码深度` skill_depth=`技能深度`*
完成后返回*[调用 build step context](agent.build_step_context(agent=`智能体`, task=`任务`, source_depth=`源码深度`, skill_depth=`技能深度`))*。
---
## 提取工具名
+ `回复`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 回复 | any | 必填 | 待解析的模型回复,不直接作为执行授权 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。 |
这里使用`回复`。
解析人可读调用行:`CALL:<名>` 或 `调用:<名>` / `调用:<名>`。
**esc = > json.parse text={"nl":"\n"}**
**nl = > json.get value=`esc` key="nl"**
**text = > trim value=`回复`**
**lines = > split value=`text` sep=`nl`**
**found = 空**
这里按行识别工具协议,先去掉行两端空白,再按半角冒号分隔。CALL 或“调用”作为前缀时,后面的片段成为候选工具名;没有匹配则返回空值。当前实现不把任意自然语言中的函数名当作请求,也不在这里执行函数。候选值仍要经过运行工具的白名单判断。
注意实际分隔符是半角冒号,全角冒号的示意不能保证被本函数识别。同一回复包含多个有效协议行时,后面的匹配会覆盖前面的候选;工具名中的额外冒号也不作为完整名称保留。生成端应只输出一条明确的 CALL:name,避免依赖这种兼容解析。
保留所需的文本分隔符,先**esc = [Keep the exact separator](table.put(in=None, at="nl", value="\n"))**。
得到**`nl` = [读取 nl 字段](json.get(value=`esc`, key="nl"))**。
得到**`text` = [调用 trim](trim(value=`回复`))**。
得到**`lines` = [调用 split](split(value=`text`, sep=`nl`))**。
得到**found = 空**。
- [line](遍历 `lines` 为 `line`)
**t = > trim value=`line`**
**parts = > split value=`t` sep=:**
**n = > len value=`parts`**
得到**`t` = [调用 trim](trim(value=`line`))**。
得到**`parts` = [调用 split](split(value=`t`, sep=":"))**。
得到**`n` = [调用 len](len(value=`parts`))**。
1. `n` > 1
**head = > at value=`parts` index=0**
**head = > trim value=`head`**
**rest = > at value=`parts` index=1**
**rest = > trim value=`rest`**
得到**`head` = [调用 at](at(value=`parts`, index=0))**。
得到**`head` = [调用 trim](trim(value=`head`))**。
得到**`rest` = [调用 at](at(value=`parts`, index=1))**。
得到**`rest` = [调用 trim](trim(value=`rest`))**。
1. `head` == CALL
**found = rest**
得到**found = rest**。
2. `head` == 调用
**found = rest**
得到**found = rest**。
3. *
**_ = 1**
2. *
**_ = 1**
*found*
完成后返回*found*。
---
## 运行工具
+ `工具`
+ `名`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 |
| 名 | any | 必填 | 本操作注册或查找的名称 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。 |
这里使用`工具`、`名`。
白名单校验后,经 `lib/子任务`(`启动 函数=` → `等待`)调用 runbook 中的 `##`。
**allowed = > agent_tool_allowed tools=`工具` name=`名`**
得到**`allowed` = [调用 tool allowed](agent_tool_allowed(tools=`工具`, name=`名`))**。
1. `allowed`
**id = > 子任务.启动 函数=`名`**
*> 子任务.等待 id=`id`*
得到**`id` = [调用 启动](子任务.启动(函数=`名`))**。
完成后返回*[调用 等待](子任务.等待(id=`id`))*。
2. *
**msg = "Tool not allowed:"**
*msg + `名`*
得到**msg = "Tool not allowed:"**。
完成后返回*msg + `名`*。
# 智能体
+ `大模型`
+ `工具`
+ `站立提示`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 大模型 | any | 必填 | 按提供方配置创建的模型资源 |
| 工具 | any | 必填 | 明确允许的工具白名单或工具记录 |
| 站立提示 | any | 必填 | 作者提供的常驻任务说明 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 加载 ABI v2 agent 插件(会话袋 + 上下文查询)。 |
这里使用`大模型`、`工具`、`站立提示`。
加载 ABI v2 agent 插件(会话袋 + 上下文查询)。
**p = > 插件.原生路径 名="agent"**
创建记录同时注册历史会话;传入的模型应提供运行方法,工具来自作者明确给出的清单。构造成功表示资源就绪,不表示已执行任务。
得到**`p` = [定位已安装的原生插件](插件.原生路径(名="agent"))**。
1. `p`
> 插件.加载 路径=`p`
这里**[调用 加载](插件.加载(路径=`p`))**。
2. *
> 打印 内容=ext/ai/智能体: 未找到原生 agent 插件(请先 cargo build -p marqdo_plugin_agent 或 marqdo ext add agent)
> 系统.退出 码=1
这里**[输出本步已准备的消息](打印(内容="ext/ai/智能体: 未找到原生 agent 插件(请先 cargo build -p marqdo_plugin_agent 或 marqdo ext add agent)"))**。
这里**[调用 退出](系统.退出(码=1))**。
得到**`id` = [调用 alloc](agent_alloc())**。
**id = > agent_alloc**
`h` =
| _type | id | model | tools |
@@ -97,49 +142,81 @@ description: 文档驱动智能体 v2 — 单步 / 多步 / 运行;技能编
| 智能体 | `id` | `大模型` | `工具` |
1. `站立提示`
**h = table.put in=`h` at="standing" value=`站立提示`**
得到**`h` = [在新记录中设置 standing 字段](table.put(in=`h`, at="standing", value=`站立提示`))**。
2. *
**_ = 1**
*h*
完成后返回*h*。
## 清空历史
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 清空本智能体 id 的插件会话袋。 |
清空本智能体 id 的插件会话袋。
**id = > json.get value=`自` key="id"**
> agent_history_clear id=`id`
****
得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。
这里**[调用 history clear](agent_history_clear(id=`id`))**。
完成后返回*None*。
## 试跑
+ `路径`=None
+ `源码`=None
+ `根目录`=None
+ `写入路径`=None
+ `文本`=None
+ `提交`=真
+ `配置`=default
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 授权根目录内的文件路径 |
| 源码 | any | None | 本次检查或试跑的源码文本 |
| 根目录 | any | None | 明确选择的工程或试运行根目录 |
| 写入路径 | any | None | 明确的产物路径,或不写出时使用 None |
| 文本 | any | None | 本操作接收的文本 |
| 提交 | any | True | 是否在验证完成后晋升试运行变更 |
| 配置 | any | "default" | 试运行使用的能力配置 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。 |
这里使用`路径`=None、`源码`=None、`根目录`=None、`写入路径`=None、`文本`=None、`提交`=True、`配置`="default"。
O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成功 `提交` 前不变)。
*> agent.trial path=`路径` source=`源码` root=`根目录` write_path=`写入路径` text=`文本` commit=`提交` profile=`配置`*
完成后返回*[调用 trial](agent.trial(path=`路径`, source=`源码`, root=`根目录`, write_path=`写入路径`, text=`文本`, commit=`提交`, profile=`配置`))*。
## 单步
+ `任务`
+ `写回`=真
+ `流式`=假
+ `打印增量`=假
+ `沙盒`=假
+ `沙盒配置`=default
原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 *map*(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 写回 | any | True | 是否向任务文档写回观察结果 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 沙盒 | any | False | 是否采用 CoW 试运行路径 |
| 沙盒配置 | any | "default" | CoW 试运行能力配置 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。 流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。 |
这里使用`任务`、`写回`=True、`流式`=False、`打印增量`=False、`沙盒`=False、`沙盒配置`="default"。
原子一轮:上下文 → 大模型 → 可选子任务调工具。返回 map 记录(`status`、`task`、`decision`;成功含 `result`,可选 `tool` / `tool_result`;失败含 `error`)。默认(`写回=真`)将结果写入调用行下的命名槽 `ok` / `error`;传 `写回=假` 可关闭。
流式=真 时走 SSE;打印增量=真 边读边打印。返回 map 仍是最终 result 文本。`沙盒=真` 时结果附带沙盒配置行。
**ctx = > 构建单步上下文 智能体=`自` 任务=`任务`**
**id = > json.get value=`自` key="id"**
**model = > json.get value=`自` key="model"**
**tools = > json.get value=`自` key="tools"**
默认会写回调用文档;若只想观察结果,请显式传入写回=False,避免演示修改任务源码。这一轮先把用户任务写入当前会话历史,再用调用点上下文请求模型。流式分支先收集事件得到最终文本,普通分支直接取得回复。随后只把明确的工具协议视作调用候选;其余文字作为回答保留。中文兼容面使用模型的运行方法,并不要求调用方假装它具有英文资源的全部接口。
有工具候选时,运行工具负责核对作者白名单并等待子任务。拒绝结果进入 error 字段;成功结果被序列化后提供给模型,再形成面向用户的回答。tool_result 因而保存的是序列化文本,消费它时不要误当原始业务记录。没有工具候选时直接使用本次回复,避免重复请求。
这一步会把最终助手回复追加到同一历史,并按写回开关将完整记录放入调用点的 ok 或 error 槽。演示或只读任务应明确关闭写回,生产流程则要为实际文件操作准备权限。返回记录中的 status、decision、result 和工具字段分别说明流程状态、原始决定与最终答案,它们不能相互替代;任务特有的正确性仍由调用方验证。
这里的沙盒开关只给返回记录附加所选配置行,不会把上述模型或工具调用迁移到 CoW 环境。需要隔离试运行,应调用试跑入口或使用具有实际 CoW 执行边界的工程运行流程。不要依据 sandbox_profile 字段的存在宣称副作用已经隔离。写回失败、插件失败和传输失败仍沿既有运行诊断报告,函数没有通用事务回滚能力。
开发此方法时,先使用只返回固定文本的离线模型替身确认上下文、历史与结果字段,再分别验证工具允许、工具拒绝和写回开关。涉及真实模型的测试还应覆盖流式结束、错误事件和无文本结果。保持这两类验证分开,才能判断错误来自编排还是传输,避免用一次线上回答掩盖未执行的分支。
得到**`ctx` = [调用 构建单步上下文](构建单步上下文(智能体=`自`, 任务=`任务`))**。
得到**`id` = [读取 id 字段](json.get(value=`自`, key="id"))**。
得到**`model` = [读取 model 字段](json.get(value=`自`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`自`, key="tools"))**。
`user_turn` =
@@ -147,17 +224,18 @@ O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成
|------|---------|
| user | `任务` |
> agent_history_append id=`id` item=`user_turn`
这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`user_turn`))**。
1. `流式`
**evs = > model.运行 提示=`ctx` 流式=真 打印增量=`打印增量`**
**reply = > 大模型.流式结果 事件=`evs`**
得到**`evs` = [调用 运行](model.运行(提示=`ctx`, 流式=True, 打印增量=`打印增量`))**。
得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs`))**。
2. *
**reply = > model.运行 提示=`ctx`**
得到**`reply` = [调用 运行](model.运行(提示=`ctx`))**。
得到**`reply` = [调用 trim](trim(value=`reply`))**。
得到**decision = reply**。
得到**`tool_name` = [调用 提取工具名](提取工具名(回复=`reply`))**。
**reply = > trim value=`reply`**
**decision = reply**
**tool_name = > 提取工具名 回复=`reply`**
`out` =
| status | task | decision |
@@ -165,208 +243,280 @@ O1 可选沙盒试跑。转发 `agent.trial`(表风格返回;宿主树在成
| ok | `任务` | `decision` |
1. `tool_name`
**tool_out = > 运行工具 工具=`tools` 名=`tool_name`**
**tool_s = > json.stringify value=`tool_out`**
**deny = > split value=`tool_s` sep="Tool not allowed"**
**deny_n = > len value=`deny`**
得到**`tool_out` = [调用 运行工具](运行工具(工具=`tools`, 名=`tool_name`))**。
得到**`tool_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`tool_out`))**。
得到**`deny` = [调用 split](split(value=`tool_s`, sep="Tool not allowed"))**。
得到**`deny_n` = [调用 len](len(value=`deny`))**。
1. `deny_n` > 1
**out = table.put in=`out` at="status" value="error"**
**out = table.put in=`out` at="error" value=`tool_s`**
**reply = tool_s**
得到**`out` = [在新记录中设置 status 字段](table.put(in=`out`, at="status", value="error"))**。
得到**`out` = [在新记录中设置 error 字段](table.put(in=`out`, at="error", value=`tool_s`))**。
得到**reply = tool_s**。
2. *
**task_s = > json.stringify value=`任务`**
**fp = "The user asked:"**
**fp = fp + task_s**
**fp = fp + ". Tool"**
**fp = fp + tool_name**
**fp = fp + "ran via subtask and returned:"**
**fp = fp + tool_s**
**fp = fp + ". Reply to the user briefly."**
得到**`task_s` = [将结构化值编码为 JSON 文本](json.stringify(value=`任务`))**。
得到**fp = "The user asked:"**。
得到**fp = fp + task_s**。
得到**fp = fp + ". Tool"**。
得到**fp = fp + tool_name**。
得到**fp = fp + "ran via subtask and returned:"**。
得到**fp = fp + tool_s**。
得到**fp = fp + ". Reply to the user briefly."**。
1. `流式`
**evs2 = > model.运行 提示=`fp` 流式=真 打印增量=`打印增量`**
**reply = > 大模型.流式结果 事件=`evs2`**
得到**`evs2` = [调用 运行](model.运行(提示=`fp`, 流式=True, 打印增量=`打印增量`))**。
得到**`reply` = [调用 流式结果](大模型.流式结果(事件=`evs2`))**。
2. *
**reply = > model.运行 提示=`fp`**
**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`**
得到**`reply` = [调用 运行](model.运行(提示=`fp`))**。
得到**`out` = [在新记录中设置 tool 字段](table.put(in=`out`, at="tool", value=`tool_name`))**。
得到**`out` = [在新记录中设置 tool_result 字段](table.put(in=`out`, at="tool_result", value=`tool_s`))**。
得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。
2. *
**out = table.put in=`out` at="result" value=`reply`**
得到**`out` = [在新记录中设置 result 字段](table.put(in=`out`, at="result", value=`reply`))**。
`as_turn` =
| role | content |
|------|---------|
| assistant | `reply` |
> agent_history_append id=`id` item=`as_turn`
这里**[将本项追加到新列表](agent_history_append(id=`id`, item=`as_turn`))**。
1. `沙盒`
**配置行 = sandbox.profile name=`沙盒配置`**
**out = table.put in=`out` at="sandbox_profile" value=`配置行`**
得到**`配置行` = [调用 profile](sandbox.profile(name=`沙盒配置`))**。
得到**`out` = [在新记录中设置 sandbox_profile 字段](table.put(in=`out`, at="sandbox_profile", value=`配置行`))**。
2. *
**_ = 1**
1. `写回`
**body = > json.stringify value=`out`**
**st = > json.get value=`out` key="status"**
得到**`body` = [将结构化值编码为 JSON 文本](json.stringify(value=`out`))**。
得到**`st` = [读取 status 字段](json.get(value=`out`, key="status"))**。
1. `st` == "ok"
> 自写回.写回 值=`body` 键="ok"
这里**[调用 写回](自写回.写回(值=`body`, 键="ok"))**。
2. *
> 自写回.写回 值=`body` 键="error"
这里**[调用 写回](自写回.写回(值=`body`, 键="error"))**。
2. *
**_ = 1**
*out*
完成后返回*out*。
## 工程预检
+ `任务`
+ `根目录`="."
+ `知识目录`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 根目录 | any | "." | 明确选择的工程或试运行根目录 |
| 知识目录 | any | None | 检索和写回所用的知识目录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | Engineering First Information 门闩。转发 `agent.preflight`。 |
这里使用`任务`、`根目录`="."、`知识目录`=None。
Engineering First Information 门闩。转发 `agent.preflight`。
*> agent.preflight task=`任务` root=`根目录` marqdo_dir=`知识目录`*
完成后返回*[调用 preflight](agent.preflight(task=`任务`, root=`根目录`, marqdo_dir=`知识目录`))*。
## 多步
+ `目标`
+ `工作簿目录`=None
+ `工作簿`=None
+ `最大轮次`=4
+ `确认分解`=False
+ `写回`=True
+ `骨架`=single
+ `复用`=True
+ `优化`=False
+ `强制`=False
+ `软命中`=False
+ `近义命中`=True
+ `近义阈值`=0.78
+ `晋升`=True
+ `知识库目录`=.marqdo/agent-kb
+ `改进周期`=3
+ `探索次数`=3
+ `流式`=False
+ `打印增量`=False
+ `轨迹`=False
+ `工程预检`=False
+ `工程知识目录`=.marqdo
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 目标 | any | 必填 | 当前人类任务目标 |
| 工作簿目录 | any | None | 本次规划拥有的工作簿目录 |
| 工作簿 | any | None | 工作簿路径或工作簿引用 |
| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 |
| 确认分解 | any | False | 是否要求确认任务分解 |
| 写回 | any | True | 是否向任务文档写回观察结果 |
| 骨架 | any | "single" | 用于生成工作簿的源码模板 |
| 复用 | any | True | 是否先检索已有能力 |
| 优化 | any | False | 是否采用已说明的改进路径 |
| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 |
| 软命中 | any | False | 是否考虑有界近似匹配 |
| 近义命中 | any | True | 是否考虑近义能力候选 |
| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 |
| 晋升 | any | True | 是否允许将已验证证据晋升 |
| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 |
| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 |
| 探索次数 | any | 3 | 有界探索尝试次数上限 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 轨迹 | any | False | 是否保留已说明的执行轨迹 |
| 工程预检 | any | False | 是否进行工程能力复用预检 |
| 工程知识目录 | any | ".marqdo" | 工程检索使用的知识目录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 多步工作簿默认写入 OKF `知识库目录/resources/<slug>.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。 |
这里使用`目标`、`工作簿目录`=None、`工作簿`=None、`最大轮次`=4、`确认分解`=False、`写回`=True、`骨架`="single"、`复用`=True、`优化`=False、`强制`=False、`软命中`=False、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`知识库目录`=".marqdo/agent-kb"、`改进周期`=3、`探索次数`=3、`流式`=False、`打印增量`=False、`轨迹`=False、`工程预检`=False、`工程知识目录`=".marqdo"。
多步工作簿默认写入 OKF `知识库目录/resources/<slug>.mq.md`;仅当传入 `工作簿目录` 时才用临时 runs。转发至英文 `agent.plan`。`流式` / `打印增量` / `轨迹` 对应 `stream` / `echo` / `trace`;`软命中` → `soft_match`;`近义命中` / `近义阈值` → `near_match` / `near_threshold`。`工程预检` → `eng_preflight`。
**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.plan goal=`目标` workbook_dir=`工作簿目录` workbook=`工作簿` max_rounds=`最大轮次` confirm=`确认分解` writeback=`写回` skeleton=`骨架` reuse=`复用` optimize=`优化` force=`强制` soft_match=`软命中` near_match=`近义命中` near_threshold=`近义阈值` promote=`晋升` kb_dir=`知识库目录` improve_every=`改进周期` explore_n=`探索次数` stream=`流式` echo=`打印增量` trace=`轨迹` eng_preflight=`工程预检` marqdo_dir=`工程知识目录`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 plan](en.plan(goal=`目标`, workbook_dir=`工作簿目录`, workbook=`工作簿`, max_rounds=`最大轮次`, confirm=`确认分解`, writeback=`写回`, skeleton=`骨架`, reuse=`复用`, optimize=`优化`, force=`强制`, soft_match=`软命中`, near_match=`近义命中`, near_threshold=`近义阈值`, promote=`晋升`, kb_dir=`知识库目录`, improve_every=`改进周期`, explore_n=`探索次数`, stream=`流式`, echo=`打印增量`, trace=`轨迹`, eng_preflight=`工程预检`, marqdo_dir=`工程知识目录`))*。
## 解析
+ `任务`
+ `知识库目录`=.marqdo/agent-kb
+ `近义命中`=True
+ `近义阈值`=0.78
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 |
| 近义命中 | any | True | 是否考虑近义能力候选 |
| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 技能解析(v2):exact → alias → canonical → near。 |
这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`近义命中`=True、`近义阈值`=0.78。
技能解析(v2):exact → alias → canonical → near。
**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.resolve task=`任务` kb_dir=`知识库目录` near_match=`近义命中` near_threshold=`近义阈值`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 resolve](en.resolve(task=`任务`, kb_dir=`知识库目录`, near_match=`近义命中`, near_threshold=`近义阈值`))*。
## 记录情景
+ `任务`
+ `状态`=ok
+ `结果`=None
+ `模式`=explore
+ `技能`=none
+ `观察`=None
+ `工作簿`=None
+ `缓存`=None
+ `匹配`=None
+ `大模型次数`=0
+ `工具次数`=0
+ `错误`=None
+ `记忆目录`=.marqdo/agent-memory
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 状态 | any | "ok" | 当前结构化执行状态 |
| 结果 | any | None | 前一步返回的结构化结果 |
| 模式 | any | "explore" | 本函数说明支持的操作模式 |
| 技能 | any | "none" | 准备检查或调用的技能引用 |
| 观察 | any | None | 保留给后续步骤的工具或工作簿观察 |
| 工作簿 | any | None | 工作簿路径或工作簿引用 |
| 缓存 | any | None | 是否使用已说明的结果缓存 |
| 匹配 | any | None | 已解析的能力匹配结果 |
| 大模型次数 | any | 0 | 实际观测到的模型调用次数 |
| 工具次数 | any | 0 | 实际观测到的工具调用次数 |
| 错误 | any | None | 可恢复失败记录 |
| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将一次执行沉淀为 `.mq.md` 情景记忆。 |
这里使用`任务`、`状态`="ok"、`结果`=None、`模式`="explore"、`技能`="none"、`观察`=None、`工作簿`=None、`缓存`=None、`匹配`=None、`大模型次数`=0、`工具次数`=0、`错误`=None、`记忆目录`=".marqdo/agent-memory"。
将一次执行沉淀为 `.mq.md` 情景记忆。
**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.record_episode task=`任务` status=`状态` result=`结果` mode=`模式` skill=`技能` observation=`观察` workbook=`工作簿` cache=`缓存` match=`匹配` llm_calls=`大模型次数` tool_calls=`工具次数` error=`错误` memory_dir=`记忆目录`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 record episode](en.record_episode(task=`任务`, status=`状态`, result=`结果`, mode=`模式`, skill=`技能`, observation=`观察`, workbook=`工作簿`, cache=`缓存`, match=`匹配`, llm_calls=`大模型次数`, tool_calls=`工具次数`, error=`错误`, memory_dir=`记忆目录`))*。
## 尝试学习
+ `任务`
+ `知识库目录`=.marqdo/agent-kb
+ `记忆目录`=.marqdo/agent-memory
+ `改进周期`=3
+ `晋升`=True
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 |
| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 |
| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 |
| 晋升 | any | True | 是否允许将已验证证据晋升 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。 |
这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`改进周期`=3、`晋升`=True。
情景足够时:归纳 → 合成候选 → 编译 → 可选晋升为 `llm_free` 技能。
**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.maybe_learn task=`任务` kb_dir=`知识库目录` memory_dir=`记忆目录` improve_every=`改进周期` promote=`晋升`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 maybe learn](en.maybe_learn(task=`任务`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, improve_every=`改进周期`, promote=`晋升`))*。
## 运行
+ `任务`
+ `知识库目录`=.marqdo/agent-kb
+ `记忆目录`=.marqdo/agent-memory
+ `学习`=True
+ `校验`=True
+ `写回`=True
+ `复用`=True
+ `近义命中`=True
+ `近义阈值`=0.78
+ `晋升`=True
+ `改进周期`=3
+ `探索次数`=3
+ `最大轮次`=4
+ `流式`=False
+ `打印增量`=False
+ `轨迹`=False
+ `强制`=False
+ `路由`=auto
+ `路由模型`=None
+ `沙盒`=False
+ `沙盒配置`=default
+ `工程预检`=True
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 |
| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 |
| 学习 | any | True | 是否记录观察或进行学习 |
| 校验 | any | True | 是否运行已说明的校验器 |
| 写回 | any | True | 是否向任务文档写回观察结果 |
| 复用 | any | True | 是否先检索已有能力 |
| 近义命中 | any | True | 是否考虑近义能力候选 |
| 近义阈值 | any | 0.78 | 近义匹配所需的最低得分 |
| 晋升 | any | True | 是否允许将已验证证据晋升 |
| 改进周期 | any | 3 | 触发一次改进前所需的观察次数 |
| 探索次数 | any | 3 | 有界探索尝试次数上限 |
| 最大轮次 | any | 4 | 允许的工作簿规划轮数上限 |
| 流式 | any | False | 是否使用流式调用 |
| 打印增量 | any | False | 是否输出流式增量文本 |
| 轨迹 | any | False | 是否保留已说明的执行轨迹 |
| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 |
| 路由 | any | "auto" | 路由配置或已选路由 |
| 路由模型 | any | None | 用于路由决策的模型资源 |
| 沙盒 | any | False | 是否采用 CoW 试运行路径 |
| 沙盒配置 | any | "default" | CoW 试运行能力配置 |
| 工程预检 | any | True | 是否进行工程能力复用预检 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | v2+P4 主入口:自适应路由 → 执行 → 记录情景 → 尝试学习(技能 + 策略)。`路由`=`auto`&#124;`marqdo`&#124;`small-llm`&#124;`llm`(`jev` 为 `small-llm` 兼容别名);决策器用 `路由模型`(任意 llm 句柄)。`沙盒=真` 走 CoW 试跑;`工程预检` 对应 `efi`。 |
这里使用`任务`、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`学习`=True、`校验`=True、`写回`=True、`复用`=True、`近义命中`=True、`近义阈值`=0.78、`晋升`=True、`改进周期`=3、`探索次数`=3、`最大轮次`=4、`流式`=False、`打印增量`=False、`轨迹`=False、`强制`=False、`路由`="auto"、`路由模型`=None、`沙盒`=False、`沙盒配置`="default"、`工程预检`=True。
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=`路由模型` sandbox=`沙盒` sandbox_profile=`沙盒配置` efi=`工程预检`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 run](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=`工程预检`))*。
## 路由
+ `任务`
+ `后端`=auto
+ `知识库目录`=.marqdo/agent-kb
+ `记忆目录`=.marqdo/agent-memory
+ `阈值`=0.78
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 任务 | any | 必填 | 本次执行的任务文本或结构化记录 |
| 后端 | any | "auto" | 明确选择的执行或模型后端 |
| 知识库目录 | any | ".marqdo/agent-kb" | 知识库的明确目录 |
| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 |
| 阈值 | any | 0.78 | 当前操作要求满足的策略阈值 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。 |
这里使用`任务`、`后端`="auto"、`知识库目录`=".marqdo/agent-kb"、`记忆目录`=".marqdo/agent-memory"、`阈值`=0.78。
自适应路由(阶段 4):`marqdo` / `small-llm` / `llm` / `auto`(`jev`→别名)。
**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.route task=`任务` backend=`后端` kb_dir=`知识库目录` memory_dir=`记忆目录` threshold=`阈值`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 route](en.route(task=`任务`, backend=`后端`, kb_dir=`知识库目录`, memory_dir=`记忆目录`, threshold=`阈值`))*。
## 编译策略
+ `记忆目录`=.marqdo/agent-memory
+ `最少证据`=3
+ `强制`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 记忆目录 | any | ".marqdo/agent-memory" | 情景或策略记忆所在目录 |
| 最少证据 | any | 3 | 允许晋升前所需的证据数量 |
| 强制 | any | False | 本操作支持的显式覆盖选项,不绕过宿主授权 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。 |
这里使用`记忆目录`=".marqdo/agent-memory"、`最少证据`=3、`强制`=False。
策略编译:稳定的 task→skill 映射 → `policies/router.mq.md`。
**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.compile_policy memory_dir=`记忆目录` min_evidence=`最少证据` force=`强制`*
得到**`model` = [读取 model 字段](json.get(value=`self`, key="model"))**。
得到**`tools` = [读取 tools 字段](json.get(value=`self`, key="tools"))**。
得到**`standing` = [读取 standing 字段](json.get(value=`self`, key="standing"))**。
得到**`en` = [调用 agent](agent.agent(model=`model`, tools=`tools`, standing=`standing`))**。
完成后返回*[调用 compile policy](en.compile_policy(memory_dir=`记忆目录`, min_evidence=`最少证据`, force=`强制`))*。
+127 -28
View File
@@ -7,59 +7,158 @@ import:
sandbox: ext/ai/sandbox.mq.md
---
## 打开
+ `根`=None
本文件提供中文试跑门面,对应[试跑实现](sandbox.mq.md)。先读[中文入口](索引.mq.md)了解模型调用与 CoW 试跑的区别。试跑产生的文件变更和诊断供调用者检查,提升变更必须走已有显式流程;试跑返回不等于宿主工作区已经更新。保持失败、取消和提升的结果可区分,避免复制一份隔离实现。
*> sandbox.open root=`根`*
## 打开
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 根 | any | None | 当前会话或工程明确授权的根目录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。 |
这里使用`根`=None。
按根目录与能力配置打开同源 CoW 试运行会话,不立即修改真实文件树。
完成后返回*[调用 open](sandbox.open(root=`根`))*。
## 写入
+ `id`
+ `路径`
+ `文本`
*> sandbox.write id=`id` path=`路径` text=`文本`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 路径 | any | 必填 | 授权根目录内的文件路径 |
| 文本 | any | 必填 | 本操作接收的文本 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 把文本写入试运行会话的覆盖层,提交前不改真实文件。 |
这里使用`id`、`路径`、`文本`。
把文本写入试运行会话的覆盖层,提交前不改真实文件。
完成后返回*[调用 write](sandbox.write(id=`id`, path=`路径`, text=`文本`))*。
## 读取
+ `id`
+ `路径`
*> sandbox.read id=`id` path=`路径`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 路径 | any | 必填 | 授权根目录内的文件路径 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。 |
这里使用`id`、`路径`。
透过试运行覆盖层读取文本,遵循白化删除和下层读取语义。
完成后返回*[调用 read](sandbox.read(id=`id`, path=`路径`))*。
## 删除
+ `id`
+ `路径`
*> sandbox.remove id=`id` path=`路径`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 路径 | any | 必填 | 授权根目录内的文件路径 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 在试运行覆盖层标记删除,不直接删除宿主文件。 |
这里使用`id`、`路径`。
在试运行覆盖层标记删除,不直接删除宿主文件。
完成后返回*[调用 remove](sandbox.remove(id=`id`, path=`路径`))*。
## 差异
+ `id`
*> sandbox.diff id=`id`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 读取会话中的真实变更清单,供决定提交或丢弃。 |
这里使用`id`。
读取会话中的真实变更清单,供决定提交或丢弃。
完成后返回*[调用 diff](sandbox.diff(id=`id`))*。
## 提交
+ `id`
*> sandbox.commit id=`id`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。 |
这里使用`id`。
把明确选择的试运行变更提交到宿主文件树,此操作会产生真实写入。
完成后返回*[调用 commit](sandbox.commit(id=`id`))*。
## 丢弃
+ `id`
*> sandbox.discard id=`id`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 丢弃会话覆盖层中的变更,保留原始宿主文件。 |
这里使用`id`。
丢弃会话覆盖层中的变更,保留原始宿主文件。
完成后返回*[调用 discard](sandbox.discard(id=`id`))*。
## 运行
+ `id`
+ `源码`=None
+ `路径`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 源码 | any | None | 本次检查或试跑的源码文本 |
| 路径 | any | None | 授权根目录内的文件路径 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 run,保留同源能力的返回值和失败语义。 |
这里使用`id`、`源码`=None、`路径`=None。
1. `源码`
*> sandbox.run id=`id` source=`源码`*
完成后返回*[调用 run](sandbox.run(id=`id`, source=`源码`))*。
2. `路径`
*> sandbox.run id=`id` path=`路径`*
完成后返回*[调用 run](sandbox.run(id=`id`, path=`路径`))*。
3. *
> print text=沙盒.运行: 需要 源码= 或 路径=
> sys.exit code=1
这里**[输出本步已准备的消息](print(text="沙盒.运行: 需要", 源码="或", 路径=""))**。
这里**[按指定退出码结束本次运行](sys.exit(code=1))**。
## 检查
+ `id`
*> sandbox.inspect id=`id`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | 必填 | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 检查当前试运行会话及能力配置,不把检查等同于提交成功。 |
这里使用`id`。
检查当前试运行会话及能力配置,不把检查等同于提交成功。
完成后返回*[调用 inspect](sandbox.inspect(id=`id`))*。
+60
View File
@@ -0,0 +1,60 @@
---
markup: occlusion
title: AI 工程入口:模型、智能体与试运行
import:
大模型: ext/ai/大模型.mq.md
---
从本入口选择任务:[大模型](大模型.mq.md)负责提示、配置、请求和流收集;
[智能体](智能体.mq.md)提供中文使用面,[同源编排实现](agent.mq.md)负责上下文、
白名单工具、路由、工作簿和继续执行;[沙盒](沙盒.mq.md)管理试运行覆盖层及晋升。
[提供方适配入口](llm/index.mq.md)解释 HTTP 适配,[路由策略](policies/step-route.mq.md)
保留可读表数据。[英文入口](index.mq.md)给出相同职责划分。
可以先运行完全离线的流收集,不需要凭据、模型服务或原生插件:
```sh
marqdo call ext/ai/索引.mq.md 离线示例 --json
```
真实请求前明确模型基址和可信凭据,智能体还需要已构建的 agent 插件与工具白名单。
生成的调用文本不是执行授权,文件写入、网络和进程仍受宿主限制。工具失败、取消、
超预算或恢复时应保留观察与效果状态,不因继续工作簿而重复不可逆操作。
新增提供方去适配目录,公共模型行为去大模型模块,规划和上下文去智能体模块,
隔离修改去沙盒模块;保持中英文默认值与行为一致。先用本地可控替身验证成功与失败,
再在明确运行配置下测试真实服务。不能用固定完成标记冒充已经调用模型或验证了工具。
## 收集事件
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 事件 | list | 必填 | 按顺序排列的语义流或公开收集器支持的提供方事件 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | text | 由公共收集器组装的最终回答文本 |
输入`事件`是已经观测的数据,不会触发新请求或执行其中的工具文本。
本工具复用公开大模型库的 delta/text 与 done.result 收集约定,
直接返回*[把已有事件组装成最终文本](大模型.收集(事件=`事件`))*,
使离线处理与真实传输复用同一份组装规则。
## 离线示例
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | text | Hello world,由下面的实际事件组装得到 |
下面是一条确定的增量事件和一条完成事件。表格把输入内容完整列出,
读者可以比较局部文本与完成结果,不需要相信一个自报通过的标志。
此流程只验证流收集,不暗示模型服务或网络已经可用。
`事件` =
| @ | type | text | result |
|---|---|---|---|
| 1 | delta | "Hello " | None |
| 2 | done | None | "Hello world" |
最后返回*[根据列出的事件得到最终文本](收集事件(事件=`事件`))*,供下一步展示或保存。
+94 -25
View File
@@ -8,55 +8,124 @@ import:
table: lib/table.mq.md
---
Cache values belong to the selected backend and process lifetime. Use memory: only for process-local demonstration; choose and configure persistent backends explicitly. [The data entry](index.mq.md) demonstrates set, get and deletion through one receiver. Retain native ok/error fields and expiry behavior when extending this leaf; a cache miss is not evidence that a remote write succeeded.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# cache
+ `url`="memory:"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | "memory:" | Resource connection URL; scheme selects the documented backend |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis. |
Use `url`="memory:" as the inputs for this operation.
Key–value cache. Use `memory:` for in-process (tests / single process) or `redis://host:6379/0` for Redis.
> _load
*> web_cache_new url=`url`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Key–value cache. Use memory: for in-process (tests / single process) or redis://host:6379/0 for Redis.](web_cache_new(url=`url`))*.
## get
+ `key`
**url = [url](access(self, "url"))**
*> web_cache_get url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Read the cached value associated with a key; a miss is reported by the cache result. |
Use `key` as the inputs for this operation.
Read the cached value associated with a key; a miss is reported by the cache result.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Read the cached value associated with a key; a miss is reported by the cache result.](web_cache_get(url=`url`, key=`key`))*.
## set
+ `key`
+ `value`
+ `ttl`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| value | any | required | Value supplied to this operation; immutable transformations return a new value |
| ttl | any | None | Expiry duration in seconds; None uses the backend default |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Optional `ttl` is seconds until expiry. |
Use `key`, `value`, `ttl`=None as the inputs for this operation.
Optional `ttl` is seconds until expiry.
**url = [url](access(self, "url"))**
*> web_cache_set url=`url` key=`key` value=`value` ttl=`ttl`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Optional ttl is seconds until expiry.](web_cache_set(url=`url`, key=`key`, value=`value`, ttl=`ttl`))*.
## del
+ `key`
**url = [url](access(self, "url"))**
*> web_cache_del url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delete a cached key without changing other entries. |
Use `key` as the inputs for this operation.
Delete a cached key without changing other entries.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Delete a cached key without changing other entries.](web_cache_del(url=`url`, key=`key`))*.
## exists
+ `key`
**url = [url](access(self, "url"))**
*> web_cache_exists url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Test whether the cache currently holds the selected key. |
Use `key` as the inputs for this operation.
Test whether the cache currently holds the selected key.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Test whether the cache currently holds the selected key.](web_cache_exists(url=`url`, key=`key`))*.
## ttl
+ `key`
**url = [url](access(self, "url"))**
*> web_cache_ttl url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Read the remaining lifetime of a cached key using the backend TTL convention. |
Use `key` as the inputs for this operation.
Read the remaining lifetime of a cached key using the backend TTL convention.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Read the remaining lifetime of a cached key using the backend TTL convention.](web_cache_ttl(url=`url`, key=`key`))*.
+376 -131
View File
@@ -8,246 +8,491 @@ import:
table: lib/table.mq.md
---
Database receivers own a connection URL. Begin a transaction with the database receiver, use its returned identifier for transaction operations, then commit or roll back explicitly. Read [the data workflow](index.mq.md) for a real isolated SQLite example and temporary-directory ownership. Native URLs resolve differently from filesystem helpers: validate an absolute SQLite path inside the granted root before passing it to the plugin. New query behavior belongs in the native web database implementation; schema and filters remain readable tables here.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# db
+ `url`="sqlite:site.db"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | "sqlite:site.db" | Resource connection URL; scheme selects the documented backend |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods). |
Use `url`="sqlite:site.db" as the inputs for this operation.
Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` / `postgresql://…` (same CRUD methods).
> _load
*> web_db_new url=`url`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Open a database handle. URL schemes: sqlite:path (default), postgres://… / postgresql://… (same CRUD methods).](web_db_new(url=`url`))*.
## init
+ `name`
+ `fields`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | any | required | Name registered or looked up by this operation |
| fields | any | required | Readable field definitions with the columns described by this resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present. |
Use `name`, `fields` as the inputs for this operation.
Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present.
**url = [url](access(self, "url"))**
*> web_db_init url=`url` name=`name` fields=`fields`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Create a table from a schema table](web_db_init(url=`url`, name=`name`, fields=`fields`))*.
## insert
+ `table`
+ `rows`
+ `txn`=None
**url = [url](access(self, "url"))**
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| rows | any | required | Input row records to insert or process |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Insert the supplied row records, optionally within the selected open transaction. |
Use `table`, `rows`, `txn`=None as the inputs for this operation.
Insert the supplied row records, optionally within the selected open transaction.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Insert the supplied row records, optionally within the selected open transaction.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*.
## select
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
+ `txn`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter |
| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold |
| order | any | None | Field order specification, with a leading minus for descending database order |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Simple filters: one-row map of column→value (AND `=`), or rows `&#124;字段&#124;操作&#124;值&#124;` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `&#124;或&#124;` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`. |
Use `table`, `where`=None, `limit`=200, `order`=None, `txn`=None as the inputs for this operation.
Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`.
**url = [url](access(self, "url"))**
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
*[rows](access(r, "rows"))*
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`r` = [Simple filters: one-row map of column→value (AND =), or rows |字段|操作|值| (= != > >= < <= like in between is null; add |或| = 是 to join a row with OR)](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**.
Return *[rows](access(r, "rows"))*.
## paginate
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
+ `跳过`=0
+ `txn`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter |
| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold |
| order | any | None | Field order specification, with a leading minus for descending database order |
| 跳过 | any | 0 | Number of matching rows skipped before the database page |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10). |
Use `table`, `where`=None, `limit`=200, `order`=None, `跳过`=0, `txn`=None as the inputs for this operation.
Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10).
**url = [url](access(self, "url"))**
*> web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=`跳过` txn=`txn`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Like select but returns { rows, total } — the total counts rows matching where regardless of limit/跳过, so you can render 上一页 / 下一页](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=`跳过`, txn=`txn`))*.
## get
+ `table`
+ `id`
+ `txn`=None
**url = [url](access(self, "url"))**
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Read a single row by its identifier from the selected database table. |
Use `table`, `id`, `txn`=None as the inputs for this operation.
Read a single row by its identifier from the selected database table.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Read a single row by its identifier from the selected database table.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*.
## update
+ `table`
+ `id`
+ `row`
+ `txn`=None
**url = [url](access(self, "url"))**
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| row | any | required | Field/value record to apply to the selected row |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Update the supplied fields of the selected row; use update_if when a revision comparison is required. |
Use `table`, `id`, `row`, `txn`=None as the inputs for this operation.
Update the supplied fields of the selected row; use update_if when a revision comparison is required.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Update the supplied fields of the selected row; use update_if when a revision comparison is required.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*.
## update_if
+ `table`
+ `id`
+ `row`
+ `expect_col`
+ `expect_val`
+ `txn`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| row | any | required | Field/value record to apply to the selected row |
| expect_col | any | required | Column checked atomically in the conditional database update |
| expect_val | any | required | Expected current value of the comparison column |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`. |
Use `table`, `id`, `row`, `expect_col`, `expect_val`, `txn`=None as the inputs for this operation.
Conditional update (CAS) for task/revision control: `UPDATE … WHERE id=? AND expect_col=expect_val`. Returns `{ ok, updated, matched }`; `updated=0` means conflict — do not simulate atomicity with read-then-write in `.mq.md`.
**url = [url](access(self, "url"))**
*> web_db_update_if url=`url` table=`table` id=`id` row=`row` expect_col=`expect_col` expect_val=`expect_val` txn=`txn`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Conditional update (CAS) for task/revision control: UPDATE … WHERE id=? AND expect_col=expect_val](web_db_update_if(url=`url`, table=`table`, id=`id`, row=`row`, expect_col=`expect_col`, expect_val=`expect_val`, txn=`txn`))*.
## delete
+ `table`
+ `id`
+ `txn`=None
**url = [url](access(self, "url"))**
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delete the selected row, optionally inside the caller-owned transaction. |
Use `table`, `id`, `txn`=None as the inputs for this operation.
Delete the selected row, optionally inside the caller-owned transaction.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Delete the selected row, optionally inside the caller-owned transaction.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*.
## exec
+ `sql`
+ `args`=None
+ `txn`=None
**url = [url](access(self, "url"))**
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL |
| args | any | None | Arguments passed to the selected command or operation |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Execute SQL with bound arguments and return the native execution outcome. |
Use `sql`, `args`=None, `txn`=None as the inputs for this operation.
Execute SQL with bound arguments and return the native execution outcome.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Execute SQL with bound arguments and return the native execution outcome.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*.
## query
+ `sql`
+ `args`=None
+ `txn`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL |
| args | any | None | Arguments passed to the selected command or operation |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`. |
Use `sql`, `args`=None, `txn`=None as the inputs for this operation.
Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`.
**url = [url](access(self, "url"))**
*> web_db_query url=`url` sql=`sql` args=`args` txn=`txn`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Run bare SQL and return the result set — count / join / group / subqueries. Returns { rows, count }.](web_db_query(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*.
## count
+ `table`
+ `where`=None
+ `txn`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter |
| txn | any | None | Open transaction returned by the same database resource; None runs outside a transaction |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Count rows matching a `where` filter (same syntax as `select`). Returns a number. |
Use `table`, `where`=None, `txn`=None as the inputs for this operation.
Count rows matching a `where` filter (same syntax as `select`). Returns a number.
**url = [url](access(self, "url"))**
**r = > web_db_count url=`url` table=`table` where=`where` txn=`txn`**
*[count](access(r, "count"))*
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`r` = [Count rows matching a where filter (same syntax as select). Returns a number.](web_db_count(url=`url`, table=`table`, where=`where`, txn=`txn`))**.
Return *[count](access(r, "count"))*.
## migrate
+ `steps`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| steps | any | required | Ordered migration or operation records in the documented table shape |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Apply versioned SQL migrations. `steps` is a `&#124;version&#124;sql&#124;` / `&#124;版本&#124;SQL&#124;` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. |
Use `steps` as the inputs for this operation.
Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only.
**url = [url](access(self, "url"))**
*> web_db_migrate url=`url` steps=`steps`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Apply versioned SQL migrations](web_db_migrate(url=`url`, steps=`steps`))*.
## fts
+ `table`
+ `columns`
+ `name`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| columns | any | required | Column-name list or column definitions required by this operation |
| name | any | None | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. |
Use `table`, `columns`, `name`=None as the inputs for this operation.
Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only.
**url = [url](access(self, "url"))**
*> web_db_fts_create url=`url` table=`table` columns=`columns` name=`name`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Create an FTS5 index on table for the listed content columns (CSV string or list)](web_db_fts_create(url=`url`, table=`table`, columns=`columns`, name=`name`))*.
## search
+ `table`
+ `q`
+ `limit`=20
+ `name`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| q | any | required | Full-text search query |
| limit | any | 20 | Maximum returned entries or candidates; this is not a success threshold |
| name | any | None | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. |
Use `table`, `q`, `limit`=20, `name`=None as the inputs for this operation.
Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only.
**url = [url](access(self, "url"))**
*> web_db_search url=`url` table=`table` q=`q` limit=`limit` name=`name`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Full-text search (MATCH) against the FTS5 index from fts. Returns { rows, count } with a rank column (bm25). SQLite only.](web_db_search(url=`url`, table=`table`, q=`q`, limit=`limit`, name=`name`))*.
## 事务
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic. |
Begin a transaction: borrows the pooled connection exclusively and returns a
`txn` handle. Write inside it, then `提交` (commit) or `回滚` (roll back).
Every statement runs on the same connection, so a batch is atomic.
**url = [url](access(self, "url"))**
*> web_db_begin url=`url`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Begin a transaction: borrows the pooled connection exclusively and returns a Every statement runs on the same connection, so a batch is atomic.](web_db_begin(url=`url`))*.
# txn
+ `txn`
+ `url`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| txn | any | required | Open transaction returned by the same database resource; None runs outside a transaction |
| url | any | required | Resource connection URL; scheme selects the documented backend |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | A transaction handle from `db.事务`. All CRUD here runs on the transaction's connection; finish with `提交` or `回滚`. The transaction identifier and connection URL remain explicit fields for every method. |
Use `txn`, `url` as the inputs for this operation.
A transaction handle from `db.事务`. All CRUD here runs on the transaction's
connection; finish with `提交` or `回滚`.
*self*
The transaction identifier and connection URL remain explicit fields for every method.
`handle` =
| txn | url |
|---|---|
| `txn` | `url` |
Return *handle*.
## insert
+ `table`
+ `rows`
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| rows | any | required | Input row records to insert or process |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior. |
Use `table`, `rows` as the inputs for this operation.
Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior.
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Delegate to web_db_insert with the supplied inputs, preserving its result and failure behavior.](web_db_insert(url=`url`, table=`table`, rows=`rows`, txn=`txn`))*.
## select
+ `table`
+ `where`=None
+ `limit`=200
+ `order`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| where | any | None | Explicit filter map or comparison-row table; omitted means no extra filter |
| limit | any | 200 | Maximum returned entries or candidates; this is not a success threshold |
| order | any | None | Field order specification, with a leading minus for descending database order |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Same filters as `db.select`; runs inside the transaction. |
Use `table`, `where`=None, `limit`=200, `order`=None as the inputs for this operation.
Same filters as `db.select`; runs inside the transaction.
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
*[rows](access(r, "rows"))*
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
We retain **`r` = [Same filters as db.select; runs inside the transaction.](web_db_select(url=`url`, table=`table`, where=`where`, limit=`limit`, order=`order`, offset=None, txn=`txn`))**.
Return *[rows](access(r, "rows"))*.
## get
+ `table`
+ `id`
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior. |
Use `table`, `id` as the inputs for this operation.
Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior.
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Delegate to web_db_get with the supplied inputs, preserving its result and failure behavior.](web_db_get(url=`url`, table=`table`, id=`id`, txn=`txn`))*.
## update
+ `table`
+ `id`
+ `row`
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| row | any | required | Field/value record to apply to the selected row |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior. |
Use `table`, `id`, `row` as the inputs for this operation.
Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior.
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Delegate to web_db_update with the supplied inputs, preserving its result and failure behavior.](web_db_update(url=`url`, table=`table`, id=`id`, row=`row`, txn=`txn`))*.
## delete
+ `table`
+ `id`
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| id | any | required | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior. |
Use `table`, `id` as the inputs for this operation.
Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior.
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Delegate to web_db_delete with the supplied inputs, preserving its result and failure behavior.](web_db_delete(url=`url`, table=`table`, id=`id`, txn=`txn`))*.
## exec
+ `sql`
+ `args`=None
**url = [url](access(self, "url"))**
**txn = [txn](access(self, "txn"))**
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sql | any | required | SQL statement; dynamic values belong in bound args rather than concatenated SQL |
| args | any | None | Arguments passed to the selected command or operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior. |
Use `sql`, `args`=None as the inputs for this operation.
Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior.
We retain **`url` = [Read url field](access(`self`, "url"))**.
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Delegate to web_db_exec with the supplied inputs, preserving its result and failure behavior.](web_db_exec(url=`url`, sql=`sql`, args=`args`, txn=`txn`))*.
## 提交
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Commit the transaction and return its connection to the pool. |
Commit the transaction and return its connection to the pool.
**txn = [txn](access(self, "txn"))**
*> web_db_commit txn=`txn`*
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Commit the transaction and return its connection to the pool.](web_db_commit(txn=`txn`))*.
## 回滚
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Roll the transaction back (undo every write) and return its connection. |
Roll the transaction back (undo every write) and return its connection.
**txn = [txn](access(self, "txn"))**
*> web_db_rollback txn=`txn`*
We retain **`txn` = [Read txn field](access(`self`, "txn"))**.
Return *[Roll the transaction back (undo every write) and return its connection.](web_db_rollback(txn=`txn`))*.
+109 -29
View File
@@ -8,62 +8,142 @@ import:
table: lib/table.mq.md
---
This leaf projects form schema and submission operations through the native web runtime. Read [the data entry](index.mq.md) before connecting a form to persistent storage. Schema validation and route authorization are different responsibilities: an accepted field value does not authenticate its submitter. Keep schema rows, validation failures and persistence results visible when changing this resource.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# form
+ `table`=None
+ `action`=insert
+ `id`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | None | Database table name or form submission table |
| action | any | "insert" | Form submission action such as insert or update |
| id | any | None | Identifier produced or selected by the corresponding resource operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Field table + rules table; submit writes through `# db`. |
Use `table`=None, `action`="insert", `id`=None as the inputs for this operation.
Field table + rules table; submit writes through `# db`.
> _load
*> web_form_new table=`table` action=`action` id=`id`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Field table + rules table; submit writes through # db.](web_form_new(table=`table`, action=`action`, id=`id`))*.
## fields
+ `fields`
*> web_form_fields form=`self` fields=`fields`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| fields | any | required | Readable field definitions with the columns described by this resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Attach the readable field definitions to this form and return the updated resource. |
Use `fields` as the inputs for this operation.
Attach the readable field definitions to this form and return the updated resource.
Return *[Attach the readable field definitions to this form and return the updated resource.](web_form_fields(form=`self`, fields=`fields`))*.
## rules
+ `rules`
*> web_form_rules form=`self` rules=`rules`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| rules | any | required | Readable validation-rule records |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Attach validation rules to this form without submitting user data. |
Use `rules` as the inputs for this operation.
Attach validation rules to this form without submitting user data.
Return *[Attach validation rules to this form without submitting user data.](web_form_rules(form=`self`, rules=`rules`))*.
## labels
+ `submit`="Submit"
+ `cancel`="cancel"
+ `cancel_href`=""
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| submit | any | "Submit" | Displayed submit-button label |
| cancel | any | "cancel" | Displayed cancel-button label |
| cancel_href | any | "" | Navigation target of the cancel action |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Localized submit / cancel copy for rendered forms. |
Use `submit`="Submit", `cancel`="cancel", `cancel_href`="" as the inputs for this operation.
Localized submit / cancel copy for rendered forms.
*> web_form_labels form=`self` submit=`submit` cancel=`cancel` cancel_href=`cancel_href`*
Return *[Localized submit / cancel copy for rendered forms.](web_form_labels(form=`self`, submit=`submit`, cancel=`cancel`, cancel_href=`cancel_href`))*.
## validate
+ `rules`=None
+ `data`
*> web_form_validate form=`self` rules=`rules` data=`data`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| rules | any | None | Readable validation-rule records |
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Validate supplied field values and return the native validation result; this does not submit to the database. |
Use `rules`=None, `data` as the inputs for this operation.
Validate supplied field values and return the native validation result; this does not submit to the database.
Return *[Validate supplied field values and return the native validation result; this does not submit to the database.](web_form_validate(form=`self`, rules=`rules`, data=`data`))*.
## render
+ `id`=form
+ `data`=None
+ `errors`=None
*> web_form_render form=`self` id=`id` data=`data` errors=`errors`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| id | any | "form" | Identifier produced or selected by the corresponding resource operation |
| data | any | None | Structured input supplied to this adapter or resource |
| errors | any | None | Field/error record returned by validation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Render this form using its data and field errors; rendering is separate from database submission. |
Use `id`="form", `data`=None, `errors`=None as the inputs for this operation.
Render this form using its data and field errors; rendering is separate from database submission.
Return *[Render this form using its data and field errors; rendering is separate from database submission.](web_form_render(form=`self`, id=`id`, data=`data`, errors=`errors`))*.
## submit
+ `data`
+ `db`
**url = [url](access(db, "url"))**
*> web_form_submit form=`self` data=`data` url=`url`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| db | any | required | Database resource created by the public database constructor |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Submit validated form data through the selected database resource and configured action. |
Use `data`, `db` as the inputs for this operation.
Submit validated form data through the selected database resource and configured action.
We retain **`url` = [Read url field](access(`db`, "url"))**.
Return *[Submit validated form data through the selected database resource and configured action.](web_form_submit(form=`self`, data=`data`, url=`url`))*.
+121
View File
@@ -0,0 +1,121 @@
---
markup: occlusion
title: Data resources — database, cache, storage and forms
import:
cache_api: ext/data/cache.mq.md
db_api: ext/data/db.mq.md
fs: lib/fs.mq.md
path: lib/path.mq.md
---
Start here when a program needs persistent records, short-lived values, object storage or forms.
The public resource files remain the implementation: [database](db.mq.md) owns schemas and
transactions, [cache](cache.mq.md) owns expiry, [storage](storage.mq.md) owns blobs and upload
validation, and [forms](form.mq.md) separates validation, rendering and submission.
These modules use the native web plugin. In this source checkout build it with
scripts/build-web-plugin.sh; installed packages follow the web package installation route.
Commands below run at the repository root. The cache example uses memory only. The transaction example creates a SQLite file
in an owned temporary directory. Prepare an existing disposable directory and export MQ_WORK to its
absolute path; the transaction report returns work_dir for cleanup after this process exits.
Neither example needs a cloud account, credentials or an external service.
```sh
marqdo call ext/data/index.mq.md memory_cache 'key="manual"' 'value="ready"' --effects plugin --json
marqdo call ext/data/index.mq.md transaction_roundtrip "root=\"$MQ_WORK\"" --effects plugin,fs.write --fs-root "$MQ_WORK" --json
```
A resource constructor creates an object; its methods need that actual receiver. Use the free
workflow tools below for a single CLI call, or import the resource file and keep the object in
your program. Do not pass an instance method to call without its receiver or reconstruct a
transaction from guessed fields. Native resource URLs select their own backend: the marqdo
filesystem root does not rewrite a SQLite, S3 or Redis URL. Grant plugin access deliberately.
For development, keep backend operations in the native web resource implementation and expose
small, documented compositions here. Specify row/filter shapes, transaction ownership, conflicts,
expiry units and cleanup. Add an operation to its responsible leaf file and exercise it through
this facade or a real author program. Run the source-handbook regression and database/cache gold
cases on both backends. A successful transport record is not proof that a business update matched.
## memory_cache
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | text | "manual" | Key owned by this short-lived demonstration |
| value | any | "ready" | Value written and then read back from the in-process cache |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Actual cache get result; value contains the stored value |
Use `key`="manual" and `value`="ready" unless the caller supplies different data. This
workflow uses memory: storage, so values belong to the current native plugin process.
It removes its key after reading; do not use a production key for an illustrative roundtrip.
First **cache = [Create a process-local cache](cache_api.cache(url="memory:"))**.
We then **[Store the supplied value with a sixty-second expiry](> `cache`.set key=`key` value=`value` ttl=60 )**
and retain **stored = [Read the same cache entry](> `cache`.get key=`key` )**.
Once the value has been captured, **[Remove the demonstration key](> `cache`.del key=`key` )**
so another operation does not inherit it. Return *stored* as observed, including its backend fields.
## transaction_roundtrip
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| root | text | required | Absolute disposable root, matching --fs-root; native resource URLs need an absolute path |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | map | The committed row list and native commit/rollback outcomes; the second insert is rolled back |
Use the absolute `root` supplied for --fs-root. This isolated-file example shows the whole ownership sequence: create a schema, begin a transaction,
write through its receiver, finish it, and read outside it. A second transaction is explicitly
rolled back. The standalone txn constructor wraps the actual native identifier and connection URL;
it does not begin another transaction or invent an identifier.
First **directory = [Create an owned temporary directory under the granted root](fs.temp_dir(prefix="data-manual"))**.
The filesystem helper returns a root-relative name. We retain **work_dir = [Resolve that owned name against the explicit root](path.join(a=`root`, b=`directory`))**
and **[Check that this absolute directory is inside the granted filesystem root](fs.stat(path=`work_dir`))**
before giving any path to the native database. We select **database_path = [Choose the SQLite file inside that directory](path.join(a=`work_dir`, b="manual.db"))**
and select **database_url = "sqlite:" + database_path** before creating
the receiver **store = [Open only that explicitly selected SQLite resource](db_api.db(url=`database_url`))**.
The table schema is ordinary readable data; both columns and their nullability remain visible.
`fields` =
| 字段 | 类型 | 可空 |
|---|---|---|
| title | text | False |
| body | text | True |
We **[Create the isolated demonstration table](> `store`.init name="manual_notes" fields=`fields` )**
before borrowing the transaction connection. Next **native = [Begin the first transaction](> `store`.事务 )**.
To retain the exact identifier, **identifier = [Read the returned transaction identifier](access(native, "txn"))**
and **connection = [Read its connection URL](access(native, "url"))**.
Now **transaction = [Wrap those actual fields as a transaction receiver](db_api.txn(txn=`identifier`, url=`connection`))**.
`row` =
| title | body |
|---|---|
| committed | kept |
We **[Insert the first row inside its transaction](> `transaction`.insert table="manual_notes" rows=`row` )**
and keep **committed = [Commit that transaction](> `transaction`.提交 )**.
The second **cancelled = [Begin an independent transaction](> `store`.事务 )** is a native
transaction receiver, which can be used directly because its type and resource fields are retained.
We **[Insert a row that will be discarded](> `cancelled`.insert table="manual_notes" rows=`row` )**
then capture **rolled_back = [Roll back the second transaction](> `cancelled`.回滚 )**.
Finally **rows = [Read the committed state outside a transaction](> `store`.select table="manual_notes" order="id" )**.
`report` =
| rows | committed | rolled_back | work_dir |
|---|---|---|---|
| `rows` | `committed` | `rolled_back` | `work_dir` |
This example ends with one committed row. Real programs must also arrange rollback when a later
operation fails. This plugin pools open connections, so remove the owned work_dir only after this
CLI process exits and the connection is closed, including on failure. Do not assume sqlite::memory:
is in-memory through this ABI: relative resource paths are resolved against the module directory.
Return *report* with the real row data, completion records and cleanup location.
+128 -41
View File
@@ -8,81 +8,168 @@ import:
table: lib/table.mq.md
---
Use this resource for explicitly configured storage URLs; use lib/fs.mq.md for ordinary rooted filesystem operations. [The data entry](index.mq.md) explains resource ownership and the native web dependency. File bodies and byte encodings follow the native storage contract, so callers must inspect the returned operation result before publishing a resource URL. Add backend support in the existing plugin rather than encoding transport logic in callers.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/data: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/data: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# storage
+ `url`="file:data/blobs"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | "file:data/blobs" | Resource connection URL; scheme selects the documented backend |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3. |
Use `url`="file:data/blobs" as the inputs for this operation.
Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=…` talks to MinIO / S3.
> _load
*> web_storage_new url=`url`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Object storage. file:dir stores blobs on disk (offline / gold). s3://bucket?endpoint=http://127.0.0.1:9000&access_key=…&secret_key=… talks to MinIO / S3.](web_storage_new(url=`url`))*.
## put
+ `key`
+ `body`=None
+ `path`=None
+ `content_type`="application/octet-stream"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| body | any | None | Object or request content, as described by the operation |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| content_type | any | "application/octet-stream" | MIME type associated with the supplied content |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Provide either `body` (text) or `path` (local file to upload). |
Use `key`, `body`=None, `path`=None, `content_type`="application/octet-stream" as the inputs for this operation.
Provide either `body` (text) or `path` (local file to upload).
**url = [url](access(self, "url"))**
*> web_storage_put url=`url` key=`key` body=`body` path=`path` content_type=`content_type`*
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Provide either body (text) or path (local file to upload).](web_storage_put(url=`url`, key=`key`, body=`body`, path=`path`, content_type=`content_type`))*.
## get
+ `key`
**url = [url](access(self, "url"))**
*> web_storage_get url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Read the object selected by its storage key and retain the backend result shape. |
Use `key` as the inputs for this operation.
Read the object selected by its storage key and retain the backend result shape.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Read the object selected by its storage key and retain the backend result shape.](web_storage_get(url=`url`, key=`key`))*.
## delete
+ `key`
**url = [url](access(self, "url"))**
*> web_storage_delete url=`url` key=`key`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| key | any | required | Entry or field key within the selected resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Delete the selected object from this storage resource. |
Use `key` as the inputs for this operation.
Delete the selected object from this storage resource.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[Delete the selected object from this storage resource.](web_storage_delete(url=`url`, key=`key`))*.
## list
+ `prefix`=""
**url = [url](access(self, "url"))**
*> web_storage_list url=`url` prefix=`prefix`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| prefix | any | "" | Object-key or generated-name prefix |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | List object entries under the supplied key prefix. |
Use `prefix`="" as the inputs for this operation.
List object entries under the supplied key prefix.
We retain **`url` = [Read url field](access(`self`, "url"))**.
Return *[List object entries under the supplied key prefix.](web_storage_list(url=`url`, prefix=`prefix`))*.
# media
+ `storage`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| storage | any | None | Storage resource created by the public storage constructor |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`). |
Use `storage`=None as the inputs for this operation.
Offline helpers for upload validation and saving into `# storage` (also used by HTTP `app.upload`).
> _load
*> web_media_new storage=`storage`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Offline helpers for upload validation and saving into # storage (also used by HTTP app.upload).](web_media_new(storage=`storage`))*.
## validate
+ `filename`
+ `content_type`="application/octet-stream"
+ `size`
+ `max_bytes`=5242880
+ `types`=None
*> web_upload_validate filename=`filename` content_type=`content_type` size=`size` max_bytes=`max_bytes` types=`types`*
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| filename | any | required | Original or suggested filename |
| content_type | any | "application/octet-stream" | MIME type associated with the supplied content |
| size | any | required | Byte size checked by upload validation |
| max_bytes | any | 5242880 | Maximum accepted byte count; exceeding the limit must fail explicitly |
| types | any | None | Allowed MIME types for upload validation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Validate an upload filename, MIME type and byte size against explicit limits before storing anything. |
Use `filename`, `content_type`="application/octet-stream", `size`, `max_bytes`=5242880, `types`=None as the inputs for this operation.
Validate an upload filename, MIME type and byte size against explicit limits before storing anything.
Return *[Validate an upload filename, MIME type and byte size against explicit limits before storing anything.](web_upload_validate(filename=`filename`, content_type=`content_type`, size=`size`, max_bytes=`max_bytes`, types=`types`))*.
## save
+ `path`
+ `key`=None
+ `content_type`="application/octet-stream"
+ `prefix`=uploads/
+ `storage`=None
**st = storage**
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | required | Explicit filesystem path; honor the documented filesystem root and operation effects |
| key | any | None | Entry or field key within the selected resource |
| content_type | any | "application/octet-stream" | MIME type associated with the supplied content |
| prefix | any | "uploads/" | Object-key or generated-name prefix |
| storage | any | None | Storage resource created by the public storage constructor |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Save the selected local upload through the configured storage resource and return its storage result. |
Use `path`, `key`=None, `content_type`="application/octet-stream", `prefix`="uploads/", `storage`=None as the inputs for this operation.
We retain **st = storage**.
1. `st` == None
**st = [storage](access(self, "storage"))**
We retain **`st` = [Read storage field](access(`self`, "storage"))**.
2. *
*> web_upload_save storage=`st` path=`path` key=`key` content_type=`content_type` prefix=`prefix`*
Return *[Save the selected local upload through the configured storage resource and return its storage result.](web_upload_save(storage=`st`, path=`path`, key=`key`, content_type=`content_type`, prefix=`prefix`))*.
+54
View File
@@ -0,0 +1,54 @@
---
markup: occlusion
title: Linear algebra — readable matrix workflows
import:
algebra: ext/linalg/linalg.mq.md
---
Start here for a complete matrix workflow, then read [the English API](linalg.mq.md) or
[the Chinese API](线性代数.mq.md). Both expose matrix construction, symbolic expressions,
dense evaluation, solving and reusable factorization. Author matrix methods require an actual
receiver; the free functions accept the expression or matrix explicitly.
Build the native dependency with cargo build -p marqdo_plugin_linalg. This offline workflow
needs plugin permission and no files, network, live services or guessed handles:
```sh
marqdo call ext/linalg/index.mq.md solve_example --effects plugin --json
```
The source matrix and right-hand side below are visible as native matrix formulas. A factorization is a native
structured result, not a string that should be parsed by callers. Reuse a factor only with
compatible dimensions. Rendering is separate: show/draw can write SVG when a path is supplied,
so production examples must state output ownership and cleanup.
Develop matrix semantics in the native linalg implementation and keep public wrappers readable.
Add a new free operation and its EN/ZH counterpart, then update object conveniences only where
useful. Verify dimensions, singular systems and the numeric tolerance appropriate to the method;
a successful call alone does not prove that a numerical result is accurate.
## solve_example
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Native solve result with x.data equal to [[2], [1]] for the displayed system |
This example solves two x plus y equals five, and x plus three y equals five. The matrix is
factored once as LU and then reused with the right-hand side. It demonstrates the real data
path without introducing a second formula parser or embedding an external language program.
`coefficients` =
$$
\begin{bmatrix}2&1\\1&3\end{bmatrix}
$$
`right_hand_side` =
$$
\begin{pmatrix}5\\5\end{pmatrix}
$$
We create **matrix = [Construct the coefficient matrix](algebra.from_formula(formula=`coefficients`))**
and **right = [Construct the right-hand-side column](algebra.from_formula(formula=`right_hand_side`))**.
Next **factor = [Factor the coefficient matrix once](algebra.factorize(matrix=`matrix`, kind="lu"))**
retains the native factor for this system. We return *[Solve using the prepared factor](algebra.solve(b=`right`, factor=`factor`))*.
The expected entries are two and one; use the solve result fields rather than interpreting a display string.
+557 -160
View File
@@ -9,420 +9,817 @@ import:
Formula-first linear algebra (English). MatExpr simplify + display; ABI plugin.
Use [the linear-algebra workflow](index.mq.md) to build a matrix from readable formula data, factor it once and solve through its receiver. This leaf owns the shared native matrix expression API. Keep dimensions, tolerance units, lazy expressions and materialized data distinct in new operations. Native ABI changes belong in marqdo_plugin_linalg; numeric validation should compare results and residuals rather than accepting a nonempty handle.
## ensure_plugin
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Load the ABI v2 `linalg` plugin once.
**p = > plugin.native_path name="linalg"**
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="linalg"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg)
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/linalg: native linalg plugin not found (build marqdo_plugin_linalg or marqdo ext add linalg)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
## ping
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Plugin health check. |
Plugin health check.
> ensure_plugin
*> linalg_ping*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Plugin health check.](linalg_ping())*.
## mul
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix product (lazy MatMul; shape-checked). |
Use `a`, `b` as the inputs for this operation.
Matrix product (lazy MatMul; shape-checked).
> ensure_plugin
*> linalg_mul a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix product (lazy MatMul; shape-checked).](linalg_mul(a=`a`, b=`b`))*.
## add
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix / expression addition. |
Use `a`, `b` as the inputs for this operation.
Matrix / expression addition.
> ensure_plugin
*> linalg_add a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix / expression addition.](linalg_add(a=`a`, b=`b`))*.
## sub
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix / expression subtraction. |
Use `a`, `b` as the inputs for this operation.
Matrix / expression subtraction.
> ensure_plugin
*> linalg_sub a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix / expression subtraction.](linalg_sub(a=`a`, b=`b`))*.
## transpose
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Transpose expression. |
Use `expr` as the inputs for this operation.
Transpose expression.
> ensure_plugin
*> linalg_transpose expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Transpose expression.](linalg_transpose(expr=`expr`))*.
## inv
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Symbolic inverse (lazy). |
Use `expr` as the inputs for this operation.
Symbolic inverse (lazy).
> ensure_plugin
*> linalg_inv expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Symbolic inverse (lazy).](linalg_inv(expr=`expr`))*.
## simplify
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Apply MatExpr rewrite rules (R1–R5). |
Use `expr` as the inputs for this operation.
Apply MatExpr rewrite rules (R1–R5).
> ensure_plugin
*> linalg_simplify expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Apply MatExpr rewrite rules (R1–R5).](linalg_simplify(expr=`expr`))*.
## ascii
+ `expr`
+ `raw`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| raw | any | False | Whether to keep the unsimplified expression tree while rendering |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Display ASCII (default simplify first). Pass `raw=True` to keep the written tree. |
Use `expr`, `raw`=False as the inputs for this operation.
Display ASCII (default simplify first). Pass `raw=True` to keep the written tree.
> ensure_plugin
*> linalg_ascii expr=`expr` raw=`raw`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Display ASCII (default simplify first). Pass raw=True to keep the written tree.](linalg_ascii(expr=`expr`, raw=`raw`))*.
## latex
+ `expr`
+ `raw`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| raw | any | False | Whether to keep the unsimplified expression tree while rendering |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | LaTeX display. |
Use `expr`, `raw`=False as the inputs for this operation.
LaTeX display.
> ensure_plugin
*> linalg_latex expr=`expr` raw=`raw`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[LaTeX display.](linalg_latex(expr=`expr`, raw=`raw`))*.
## shape
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix shape (rows, cols). |
Use `expr` as the inputs for this operation.
Matrix shape (rows, cols).
> ensure_plugin
*> linalg_shape expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix shape (rows, cols).](linalg_shape(expr=`expr`))*.
## show
+ `expr`
+ `path`=None
+ `raw`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| raw | any | False | Whether to keep the unsimplified expression tree while rendering |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Record a formula SVG via host plot channel (default simplify). Returns the expr map. |
Use `expr`, `path`=None, `raw`=False as the inputs for this operation.
Record a formula SVG via host plot channel (default simplify). Returns the expr map.
> ensure_plugin
*> linalg_show expr=`expr` path=`path` raw=`raw`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Record a formula SVG via host plot channel (default simplify). Returns the expr map.](linalg_show(expr=`expr`, path=`path`, raw=`raw`))*.
## eye
+ `n`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| n | any | required | Matrix order |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Identity matrix of order n. |
Use `n` as the inputs for this operation.
Identity matrix of order n.
> ensure_plugin
*> linalg_eye n=`n`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Identity matrix of order n.](linalg_eye(n=`n`))*.
## zeros
+ `rows`
+ `cols`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| rows | any | required | Input row records to insert or process |
| cols | any | required | Matrix column count |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Zero matrix. |
Use `rows`, `cols` as the inputs for this operation.
Zero matrix.
> ensure_plugin
*> linalg_zeros rows=`rows` cols=`cols`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*.
## from_list
+ `data`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Dense leaf from nested list. |
Use `data` as the inputs for this operation.
Dense leaf from nested list.
> ensure_plugin
*> linalg_from_list data=`data`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Dense leaf from nested list.](linalg_from_list(data=`data`))*.
## from_formula
+ `formula`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| formula | any | required | Symbolic formula accepted by the documented parser |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf. |
Use `formula` as the inputs for this operation.
Absorb a `$$` numeric matrix formula (or nested list / dense map) as a dense leaf.
> ensure_plugin
*> linalg_from_formula formula=`formula`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Absorb a $$ numeric matrix formula (or nested list / dense map) as a dense leaf.](linalg_from_formula(formula=`formula`))*.
## explicit
+ `expr`
+ `raw`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| raw | any | False | Whether to keep the unsimplified expression tree while rendering |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Evaluate to dense (default simplify first). |
Use `expr`, `raw`=False as the inputs for this operation.
Evaluate to dense (default simplify first).
> ensure_plugin
*> linalg_explicit expr=`expr` raw=`raw`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Evaluate to dense (default simplify first).](linalg_explicit(expr=`expr`, raw=`raw`))*.
## det
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Determinant. |
Use `expr` as the inputs for this operation.
Determinant.
> ensure_plugin
*> linalg_det expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Determinant.](linalg_det(expr=`expr`))*.
## trace
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Trace. |
Use `expr` as the inputs for this operation.
Trace.
> ensure_plugin
*> linalg_trace expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Trace.](linalg_trace(expr=`expr`))*.
## solve
+ `a`=None
+ `b`
+ `factor`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | None | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| factor | any | None | Reusable factorization returned by factorize |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`. |
Use `a`=None, `b`, `factor`=None as the inputs for this operation.
Solve `a x = b` (Gaussian elimination), or reuse `factorize kind=lu` via `factor` + `b`.
> ensure_plugin
*> linalg_solve a=`a` b=`b` factor=`factor`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Solve a x = b (Gaussian elimination), or reuse factorize kind=lu via factor + b.](linalg_solve(a=`a`, b=`b`, factor=`factor`))*.
## matmul
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Dense matrix product → `linalg_dense`. |
Use `a`, `b` as the inputs for this operation.
Dense matrix product → `linalg_dense`.
> ensure_plugin
*> linalg_matmul a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Dense matrix product → linalg_dense.](linalg_matmul(a=`a`, b=`b`))*.
## kron
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Lazy Kronecker product (does not expand). |
Use `a`, `b` as the inputs for this operation.
Lazy Kronecker product (does not expand).
> ensure_plugin
*> linalg_kron a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Lazy Kronecker product (does not expand).](linalg_kron(a=`a`, b=`b`))*.
## block
+ `blocks`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| blocks | any | required | Nested row list of block matrix expressions |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Block matrix from a nested list of expressions. |
Use `blocks` as the inputs for this operation.
Block matrix from a nested list of expressions.
> ensure_plugin
*> linalg_block blocks=`blocks`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Block matrix from a nested list of expressions.](linalg_block(blocks=`blocks`))*.
## collapse
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Block-level collapse (`Block*Block` → block of products). |
Use `expr` as the inputs for this operation.
Block-level collapse (`Block*Block` → block of products).
> ensure_plugin
*> linalg_collapse expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Block-level collapse (Block*Block → block of products).](linalg_collapse(expr=`expr`))*.
## factorize
+ `matrix`
+ `kind`="lu"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| matrix | any | required | Matrix value supplied for evaluation or factorization |
| kind | any | "lu" | Operation or factorization kind listed in this function's behavior |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Dense factorization → `linalg_factor` (`kind` = `lu` &#124; `qr` &#124; `svd` &#124; `eig` &#124; `chol`). |
Use `matrix`, `kind`="lu" as the inputs for this operation.
Dense factorization → `linalg_factor` (`kind` = `lu` | `qr` | `svd` | `eig` | `chol`).
> ensure_plugin
*> linalg_factorize matrix=`matrix` kind=`kind`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Dense factorization → linalg_factor (kind = lu | qr | svd | eig | chol).](linalg_factorize(matrix=`matrix`, kind=`kind`))*.
## draw
+ `factor`
+ `kind`=None
+ `path`=None
+ `theme`="light"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| factor | any | required | Reusable factorization returned by factorize |
| kind | any | None | Operation or factorization kind listed in this function's behavior |
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| theme | any | "light" | Rendering theme token supported by the implementation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Structure SVG (`eig` &#124; `svd` &#124; `qr` &#124; `lu` &#124; `ge` &#124; `chol` &#124; `structure` &#124; `heatmap` &#124; `hinton`). Theme tokens match quantum Q8: `light` &#124; `dark` &#124; `bw`. |
Use `factor`, `kind`=None, `path`=None, `theme`="light" as the inputs for this operation.
Structure SVG (`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`). Theme tokens match quantum Q8: `light` | `dark` | `bw`.
> ensure_plugin
*> linalg_draw factor=`factor` kind=`kind` path=`path` theme=`theme`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Structure SVG (eig | svd | qr | lu | ge | chol | structure | heatmap | hinton). Theme tokens match quantum Q8: light | dark | bw.](linalg_draw(factor=`factor`, kind=`kind`, path=`path`, theme=`theme`))*.
## lstsq
+ `a`
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | Left matrix or numeric operand |
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Least squares `min &#124;&#124;a x - b&#124;&#124;` (QR if tall, SVD if wide). |
Use `a`, `b` as the inputs for this operation.
Least squares `min ||a x - b||` (QR if tall, SVD if wide).
> ensure_plugin
*> linalg_lstsq a=`a` b=`b`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Least squares min ||a x - b|| (QR if tall, SVD if wide).](linalg_lstsq(a=`a`, b=`b`))*.
## norm
+ `expr`
+ `ord`="fro"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| ord | any | "fro" | Norm order accepted by the native norm implementation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix norm: `fro` &#124; `1` &#124; `inf` &#124; `2`. Complex dense supports `fro` only. |
Use `expr`, `ord`="fro" as the inputs for this operation.
Matrix norm: `fro` | `1` | `inf` | `2`. Complex dense supports `fro` only.
> ensure_plugin
*> linalg_norm expr=`expr` ord=`ord`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix norm: fro | 1 | inf | 2. Complex dense supports fro only.](linalg_norm(expr=`expr`, ord=`ord`))*.
## cond
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Spectral condition number via SVD (`ord=2`). |
Use `expr` as the inputs for this operation.
Spectral condition number via SVD (`ord=2`).
> ensure_plugin
*> linalg_cond expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Spectral condition number via SVD (ord=2).](linalg_cond(expr=`expr`))*.
## rank
+ `expr`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| expr | any | required | Matrix expression produced by this library, or an accepted symbolic expression |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Numerical rank (SVD). |
Use `expr` as the inputs for this operation.
Numerical rank (SVD).
> ensure_plugin
*> linalg_rank expr=`expr`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Numerical rank (SVD).](linalg_rank(expr=`expr`))*.
## declare
+ `table`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | Database table name or form submission table |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env. |
Use `table` as the inputs for this operation.
Declare several matrix symbols from an `@` record table (`name` / `rows` / `cols`). Returns a map env.
> ensure_plugin
*> linalg_declare table=`table` type_tag="matrix"*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Declare several matrix symbols from an @ record table (name / rows / cols). Returns a map env.](linalg_declare(table=`table`, type_tag="matrix"))*.
## symbol
+ `name`
+ `rows`
+ `cols`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | any | required | Name registered or looked up by this operation |
| rows | any | required | Input row records to insert or process |
| cols | any | required | Matrix column count |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods). |
Use `name`, `rows`, `cols` as the inputs for this operation.
Abstract matrix symbol. Returns a `# matrix` instance (supports `+` / `*` and methods).
> ensure_plugin
*> matrix name=`name` rows=`rows` cols=`cols`*
We **[Load the native plugin required by this operation](ensure_plugin())**.
Return *[Matrix](matrix(name=`name`, rows=`rows`, cols=`cols`))*.
# matrix
+ `name`=None
+ `rows`=None
+ `cols`=None
+ `data`=None
+ `formula`=None
+ `n`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | any | None | Name registered or looked up by this operation |
| rows | any | None | Input row records to insert or process |
| cols | any | None | Matrix column count |
| data | any | None | Structured input supplied to this adapter or resource |
| formula | any | None | Symbolic formula accepted by the documented parser |
| n | any | None | Matrix order |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``. |
Use `name`=None, `rows`=None, `cols`=None, `data`=None, `formula`=None, `n`=None as the inputs for this operation.
Matrix value (`_type=matrix`). Prefer infix `A + B` / `A * B`, or methods `` `A`.T ``.
> ensure_plugin
We **[Load the native plugin required by this operation](ensure_plugin())**.
1. `formula`
*> linalg_from_formula formula=`formula`*
Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_formula(formula=`formula`))*.
2. `data`
*> linalg_from_list data=`data`*
Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_from_list(data=`data`))*.
3. `name`
*> linalg_symbol name=`name` rows=`rows` cols=`cols`*
Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_symbol(name=`name`, rows=`rows`, cols=`cols`))*.
4. `n`
*> linalg_eye n=`n`*
Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_eye(n=`n`))*.
5. `rows`
*> linalg_zeros rows=`rows` cols=`cols`*
Return *[Matrix value (_type=matrix). Prefer infix A + B / A * B, or methods A.T .](linalg_zeros(rows=`rows`, cols=`cols`))*.
6. *
> print text=ext/linalg: matrix needs name= / data= / formula= / n= / rows=
*None*
We **[Print the prepared message](print(text="ext/linalg: matrix needs", name="/", data="/", formula="/", n="/", rows=""))**.
Return *None*.
## T
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Transpose (method). |
Transpose (method).
*> linalg_transpose expr=`self`*
Return *[Transpose (method).](linalg_transpose(expr=`self`))*.
## T_ascii
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Transpose then display ASCII (auto-simplified). Handy for lecture identities. |
Transpose then display ASCII (auto-simplified). Handy for lecture identities.
**`Pt` = > linalg_transpose expr=`self`**
*> linalg_ascii expr=`Pt` raw=False*
We retain **`Pt` = [Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_transpose(expr=`self`))**.
Return *[Transpose then display ASCII (auto-simplified). Handy for lecture identities.](linalg_ascii(expr=`Pt`, raw=False))*.
## add
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix / expression addition. |
Use `b` as the inputs for this operation.
Matrix / expression addition.
*> linalg_add a=`self` b=`b`*
Return *[Matrix / expression addition.](linalg_add(a=`self`, b=`b`))*.
## sub
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix / expression subtraction. |
Use `b` as the inputs for this operation.
Matrix / expression subtraction.
*> linalg_sub a=`self` b=`b`*
Return *[Matrix / expression subtraction.](linalg_sub(a=`self`, b=`b`))*.
## mul
+ `b`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| b | any | required | Right matrix, right-hand side or numeric operand |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix / expression product. |
Use `b` as the inputs for this operation.
Matrix / expression product.
*> linalg_mul a=`self` b=`b`*
Return *[Matrix / expression product.](linalg_mul(a=`self`, b=`b`))*.
## inv
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Inverse. |
Inverse.
*> linalg_inv expr=`self`*
Return *[Inverse.](linalg_inv(expr=`self`))*.
## simplify
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Simplify MatExpr. |
Simplify MatExpr.
*> linalg_simplify expr=`self`*
Return *[Simplify MatExpr.](linalg_simplify(expr=`self`))*.
## ascii
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | ASCII display. |
ASCII display.
*> linalg_ascii expr=`self` raw=False*
Return *[ASCII display.](linalg_ascii(expr=`self`, raw=False))*.
## latex
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | LaTeX display. |
LaTeX display.
*> linalg_latex expr=`self` raw=False*
Return *[LaTeX display.](linalg_latex(expr=`self`, raw=False))*.
## explicit
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Evaluate to an explicit matrix. |
Evaluate to an explicit matrix.
*> linalg_explicit expr=`self` raw=False*
Return *[Evaluate to an explicit matrix.](linalg_explicit(expr=`self`, raw=False))*.
## det
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Determinant. |
Determinant.
*> linalg_det expr=`self`*
Return *[Determinant.](linalg_det(expr=`self`))*.
## trace
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Trace. |
Trace.
*> linalg_trace expr=`self`*
Return *[Trace.](linalg_trace(expr=`self`))*.
## show
+ `path`=None
+ `raw`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | None | Explicit filesystem path; honor the documented filesystem root and operation effects |
| raw | any | False | Whether to keep the unsimplified expression tree while rendering |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Show / export the expression. |
Use `path`=None, `raw`=False as the inputs for this operation.
Show / export the expression.
*> linalg_show expr=`self` path=`path` raw=`raw`*
Return *[Show / export the expression.](linalg_show(expr=`self`, path=`path`, raw=`raw`))*.
## eye
+ `n`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| n | any | required | Matrix order |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Identity matrix of order n. |
Use `n` as the inputs for this operation.
Identity matrix of order n.
*> linalg_eye n=`n`*
Return *[Identity matrix of order n.](linalg_eye(n=`n`))*.
## zeros
+ `rows`
+ `cols`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| rows | any | required | Input row records to insert or process |
| cols | any | required | Matrix column count |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Zero matrix. |
Use `rows`, `cols` as the inputs for this operation.
Zero matrix.
*> linalg_zeros rows=`rows` cols=`cols`*
Return *[Zero matrix.](linalg_zeros(rows=`rows`, cols=`cols`))*.
## from_list
+ `data`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| data | any | required | Structured input supplied to this adapter or resource |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix from nested list. |
Use `data` as the inputs for this operation.
Matrix from nested list.
*> linalg_from_list data=`data`*
Return *[Matrix from nested list.](linalg_from_list(data=`data`))*.
## from_formula
+ `formula`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| formula | any | required | Symbolic formula accepted by the documented parser |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Matrix from formula text. |
Use `formula` as the inputs for this operation.
Matrix from formula text.
*> linalg_from_formula formula=`formula`*
Return *[Matrix from formula text.](linalg_from_formula(formula=`formula`))*.
+45
View File
@@ -0,0 +1,45 @@
---
markup: occlusion
title: 线性代数工程入口
import:
代数: ext/linalg/线性代数.mq.md
---
从本入口运行完整矩阵流程,再阅读[中文接口](线性代数.mq.md)中每个工具的契约与说明。
[英文入口](index.mq.md)与此流程同义,表达式构造、求值、求解与分解复用共用原生实现。
对象方法必须有真实矩阵接收者;独立函数则明确传入矩阵或表达式。
在本源码工作区先用 cargo build -p marqdo_plugin_linalg 构建依赖,再执行:
```sh
marqdo call ext/linalg/索引.mq.md 求解示例 --effects plugin --json
```
本例只做离线计算,不写文件、不连接外部服务。新增能力应在原生 linalg 中实现边界算法,
公开文件补齐中英文契约和错误示例,并验证维度、奇异性及容差。绘图输出是另一种效果,
指定路径时要明确产物归属与清理责任,不把展示字符串当可计算的矩阵数据。
## 求解示例
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 原生求解记录;其中 x.data 对应列向量 [[2], [1]] |
本例求解二乘 x 加 y 等于五、x 加三乘 y 等于五。系数和右端都用原生矩阵公式给出,
先分解一次再求解,不复制另一份矩阵解析或消元程序。分解值只能用于维度兼容的系统。
`系数` =
$$
\begin{bmatrix}2&1\\1&3\end{bmatrix}
$$
`右端` =
$$
\begin{pmatrix}5\\5\end{pmatrix}
$$
先**矩阵 = [由系数公式构造矩阵](代数.自公式(公式=`系数`))**,
再**向量 = [由右端公式构造列向量](代数.自公式(公式=`右端`))**。
接着**分解 = [对系数矩阵进行一次 LU 分解](代数.分解(矩阵=`矩阵`, 类型="lu"))**,
最后返回*[复用分解结果求解本系统](代数.求解(右=`向量`, 分解=`分解`))*。
调用者应检查实际结果中的数值,不将函数调用成功等同于任意系统都满足精度要求。
+565 -161
View File
@@ -9,421 +9,825 @@ import:
公式优先的线性代数(中文)。矩阵表达式化简与展示;ABI 插件。
从[求解入口](索引.mq.md)可运行由公式构造矩阵、复用分解并求解的真实示例。本文件是中文数值门面,原生算法位于 marqdo_plugin_linalg。新增操作需说明形状、容差单位、惰性表达式和物化结果的区别;用数值与残差验证算法,不能把非空句柄当成正确结果。保持中英文入口同源,不复制一套矩阵运行时。
## 确保插件
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 完成后不返回业务数据;插件缺失会报告原因并结束运行。 |
加载 ABI v2 `linalg` 插件一次。
**p = > plugin.native_path name="linalg"**
这里只负责定位并加载现有原生库,不创建矩阵,也不会自动下载或编译插件。缺少插件时结束当前运行,让调用者修复安装路径后重试;不能返回一个伪造的矩阵句柄继续计算。加载成功后返回空值,真实数值结果由后续运算产生。
得到**`p` = [定位已安装的原生插件](plugin.native_path(name="linalg"))**。
1. `p`
> plugin.load path=`p`
这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。
2. *
> print text=ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg)
> sys.exit code=1
****
这里**[输出本步已准备的消息](print(text="ext/linalg: 未找到原生 linalg 插件(请 build marqdo_plugin_linalg 或 marqdo ext add linalg)"))**。
这里**[按指定退出码结束本次运行](sys.exit(code=1))**。
完成后返回*None*。
## 探测
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 插件探活。 |
插件探活。
> 确保插件
*> linalg_ping*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[插件探活。](linalg_ping())*。
## 乘
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵乘(惰性;检查形状)。 |
这里使用`左`、`右`。
矩阵乘(惰性;检查形状)。
> 确保插件
*> linalg_mul a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[矩阵乘(惰性;检查形状)。](linalg_mul(a=`左`, b=`右`))*。
## 加
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵 / 表达式加法。 |
这里使用`左`、`右`。
矩阵 / 表达式加法。
> 确保插件
*> linalg_add a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`左`, b=`右`))*。
## 减
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵 / 表达式减法。 |
这里使用`左`、`右`。
矩阵 / 表达式减法。
> 确保插件
*> linalg_sub a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`左`, b=`右`))*。
## 转置
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 |
这里使用`式`。
转置。
> 确保插件
*> linalg_transpose expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`式`))*。
## 逆
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 求逆。 |
这里使用`式`。
求逆。
> 确保插件
*> linalg_inv expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[求逆。](linalg_inv(expr=`式`))*。
## 化简
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 应用矩阵表达式重写规则(R1–R5)。 |
这里使用`式`。
应用矩阵表达式重写规则(R1–R5)。
> 确保插件
*> linalg_simplify expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[应用矩阵表达式重写规则(R1–R5)。](linalg_simplify(expr=`式`))*。
## 文本
+ `式`
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 展示 ASCII(默认先 化简)。`原始=True` 保留书写树。 |
这里使用`式`、`原始`=False。
展示 ASCII(默认先 化简)。`原始=True` 保留书写树。
> 确保插件
*> linalg_ascii expr=`式` raw=`原始`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[展示 ASCII(默认先 化简)。原始=True 保留书写树。](linalg_ascii(expr=`式`, raw=`原始`))*。
## 乳胶
+ `式`
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | LaTeX 展示。 |
这里使用`式`、`原始`=False。
LaTeX 展示。
> 确保插件
*> linalg_latex expr=`式` raw=`原始`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[LaTeX 展示。](linalg_latex(expr=`式`, raw=`原始`))*。
## 形状
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。 |
这里使用`式`。
形状。
> 确保插件
*> linalg_shape expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[将当前输入交给 linalg_shape,保留同源能力的返回值和失败语义。](linalg_shape(expr=`式`))*。
## 展示
+ `式`
+ `路径`=None
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 路径 | any | None | 授权根目录内的文件路径 |
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 写入公式 SVG(默认化简)。 |
这里使用`式`、`路径`=None、`原始`=False。
写入公式 SVG(默认化简)。
> 确保插件
*> linalg_show expr=`式` path=`路径` raw=`原始`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[写入公式 SVG(默认化简)。](linalg_show(expr=`式`, path=`路径`, raw=`原始`))*。
## 单位
+ `阶`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 阶 | any | 必填 | 方阵阶数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 对比特施加单位门 / 单位矩阵。 |
这里使用`阶`。
对比特施加单位门 / 单位矩阵。
> 确保插件
*> linalg_eye n=`阶`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。
## 零阵
+ `行`
+ `列`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 行 | any | 必填 | 矩阵行数 |
| 列 | any | 必填 | 矩阵列数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 零矩阵。 |
这里使用`行`、`列`。
零矩阵。
> 确保插件
*> linalg_zeros rows=`行` cols=`列`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。
## 自列表
+ `数据`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 数据 | any | 必填 | 交给本操作处理的结构化数据 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 由嵌套列表构造矩阵。 |
这里使用`数据`。
由嵌套列表构造矩阵。
> 确保插件
*> linalg_from_list data=`数据`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。
## 自公式
+ `公式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 吸收 `$$` 数值矩阵公式为稠密叶。 |
这里使用`公式`。
吸收 `$$` 数值矩阵公式为稠密叶。
> 确保插件
*> linalg_from_formula formula=`公式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[吸收 $$ 数值矩阵公式为稠密叶。](linalg_from_formula(formula=`公式`))*。
## 求值
+ `式`
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 求成稠密(默认先 化简)。 |
这里使用`式`、`原始`=False。
求成稠密(默认先 化简)。
> 确保插件
*> linalg_explicit expr=`式` raw=`原始`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[求成稠密(默认先 化简)。](linalg_explicit(expr=`式`, raw=`原始`))*。
## 行列式
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 |
这里使用`式`。
行列式。
> 确保插件
*> linalg_det expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`式`))*。
## 迹
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 |
这里使用`式`。
迹。
> 确保插件
*> linalg_trace expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`式`))*。
## 求解
+ `左`=None
+ `右`
+ `分解`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | None | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 分解 | any | None | 分解函数返回的可复用分解记录 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。 |
这里使用`左`=None、`右`、`分解`=None。
解 `左 · x = 右`,或复用 `分解`(`kind=lu`)+ `右`。
> 确保插件
*> linalg_solve a=`左` b=`右` factor=`分解`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[解 左 · x = 右,或复用 分解(kind=lu)+ 右。](linalg_solve(a=`左`, b=`右`, factor=`分解`))*。
## 稠密乘
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。 |
这里使用`左`、`右`。
稠密乘。
> 确保插件
*> linalg_matmul a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[将当前输入交给 linalg_matmul,保留同源能力的返回值和失败语义。](linalg_matmul(a=`左`, b=`右`))*。
## 克罗内克
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 惰性 Kronecker 积(默认不展开)。 |
这里使用`左`、`右`。
惰性 Kronecker 积(默认不展开)。
> 确保插件
*> linalg_kron a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[惰性 Kronecker 积(默认不展开)。](linalg_kron(a=`左`, b=`右`))*。
## 分块
+ `块`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 块 | any | 必填 | 按行列排列的分块矩阵表达式列表 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 由嵌套表达式列表构造分块矩阵。 |
这里使用`块`。
由嵌套表达式列表构造分块矩阵。
> 确保插件
*> linalg_block blocks=`块`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[由嵌套表达式列表构造分块矩阵。](linalg_block(blocks=`块`))*。
## 分块化简
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 分块级塌缩(`Block*Block` → 块乘加)。 |
这里使用`式`。
分块级塌缩(`Block*Block` → 块乘加)。
> 确保插件
*> linalg_collapse expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[分块级塌缩(Block*Block → 块乘加)。](linalg_collapse(expr=`式`))*。
## 分解
+ `矩阵`
+ `类型`="lu"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 矩阵 | any | 必填 | 本次求值或分解的矩阵值 |
| 类型 | any | "lu" | 本操作说明支持的分解或表示类型 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 稠密分解 → `linalg_factor`(`类型` = `lu` &#124; `qr` &#124; `svd` &#124; `eig` &#124; `chol`)。 |
这里使用`矩阵`、`类型`="lu"。
稠密分解 → `linalg_factor`(`类型` = `lu` | `qr` | `svd` | `eig` | `chol`)。
> 确保插件
*> linalg_factorize matrix=`矩阵` kind=`类型`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[稠密分解 → linalg_factor(类型 = lu | qr | svd | eig | chol)。](linalg_factorize(matrix=`矩阵`, kind=`类型`))*。
## 绘图
+ `分解`
+ `类型`=None
+ `路径`=None
+ `主题`="light"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 分解 | any | 必填 | 分解函数返回的可复用分解记录 |
| 类型 | any | None | 本操作说明支持的分解或表示类型 |
| 路径 | any | None | 授权根目录内的文件路径 |
| 主题 | any | "light" | 渲染主题标识 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 结构 SVG(`eig` &#124; `svd` &#124; `qr` &#124; `lu` &#124; `ge` &#124; `chol` &#124; `structure` &#124; `heatmap` &#124; `hinton`)。主题与 quantum Q8 对齐:`light` &#124; `dark` &#124; `bw`。 |
这里使用`分解`、`类型`=None、`路径`=None、`主题`="light"。
结构 SVG(`eig` | `svd` | `qr` | `lu` | `ge` | `chol` | `structure` | `heatmap` | `hinton`)。主题与 quantum Q8 对齐:`light` | `dark` | `bw`。
> 确保插件
*> linalg_draw factor=`分解` kind=`类型` path=`路径` theme=`主题`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[结构 SVG(eig | svd | qr | lu | ge | chol | structure | heatmap | hinton)。主题与 quantum Q8 对齐:light | dark | bw。](linalg_draw(factor=`分解`, kind=`类型`, path=`路径`, theme=`主题`))*。
## 最小二乘
+ `左`
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 左 | any | 必填 | 运算左侧的矩阵或表达式 |
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 最小二乘 `min &#124;&#124;左 · x - 右&#124;&#124;`(高瘦用 QR,宽用 SVD)。 |
这里使用`左`、`右`。
最小二乘 `min ||左 · x - 右||`(高瘦用 QR,宽用 SVD)。
> 确保插件
*> linalg_lstsq a=`左` b=`右`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[最小二乘 min ||左 · x - 右||(高瘦用 QR,宽用 SVD)。](linalg_lstsq(a=`左`, b=`右`))*。
## 范数
+ `式`
+ `范数`="fro"
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 范数 | any | "fro" | 范数函数支持的阶数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵范数:`fro` &#124; `1` &#124; `inf` &#124; `2`。复数稠密暂仅 `fro`。 |
这里使用`式`、`范数`="fro"。
矩阵范数:`fro` | `1` | `inf` | `2`。复数稠密暂仅 `fro`。
> 确保插件
*> linalg_norm expr=`式` ord=`范数`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[矩阵范数:fro | 1 | inf | 2。复数稠密暂仅 fro。](linalg_norm(expr=`式`, ord=`范数`))*。
## 条件数
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 谱条件数(SVD,`ord=2`)。 |
这里使用`式`。
谱条件数(SVD,`ord=2`)。
> 确保插件
*> linalg_cond expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[谱条件数(SVD,ord=2)。](linalg_cond(expr=`式`))*。
## 秩
+ `式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 式 | any | 必填 | 本库产生的矩阵表达式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 数值秩(SVD)。 |
这里使用`式`。
数值秩(SVD)。
> 确保插件
*> linalg_rank expr=`式`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[数值秩(SVD)。](linalg_rank(expr=`式`))*。
## 声明
+ `表`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 表 | any | 必填 | 可读声明记录表 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。 |
这里使用`表`。
用 `@` 记录表一次声明多个符号矩阵(`名` / `行` / `列`)。返回环境 map。
> 确保插件
*> linalg_declare table=`表` type_tag="矩阵"*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[用 @ 记录表一次声明多个符号矩阵(名 / 行 / 列)。返回环境 map。](linalg_declare(table=`表`, type_tag="矩阵"))*。
## 符号
+ `名`
+ `行`
+ `列`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 名 | any | 必填 | 本操作注册或查找的名称 |
| 行 | any | 必填 | 矩阵行数 |
| 列 | any | 必填 | 矩阵列数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。 |
这里使用`名`、`行`、`列`。
抽象矩阵符号。返回 `# 矩阵` 实例(可用 `+` / `*` 与方法)。
> 确保插件
*> 矩阵 名=`名` 行=`行` 列=`列`*
这里**[加载本操作依赖的原生插件](确保插件())**。
完成后返回*[调用 矩阵](矩阵(名=`名`, 行=`行`, 列=`列`))*。
# 矩阵
+ `名`=None
+ `行`=None
+ `列`=None
+ `数据`=None
+ `公式`=None
+ `阶`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 名 | any | None | 本操作注册或查找的名称 |
| 行 | any | None | 矩阵行数 |
| 列 | any | None | 矩阵列数 |
| 数据 | any | None | 交给本操作处理的结构化数据 |
| 公式 | any | None | 原生矩阵解析器接受的符号公式 |
| 阶 | any | None | 方阵阶数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。 |
这里使用`名`=None、`行`=None、`列`=None、`数据`=None、`公式`=None、`阶`=None。
矩阵值(`_type=矩阵`)。优先中缀 `A + B` / `A * B`,或 `` `A`.转置 ``。
> 确保插件
这里**[加载本操作依赖的原生插件](确保插件())**。
1. `公式`
*> linalg_from_formula formula=`公式`*
完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_formula(formula=`公式`))*。
2. `数据`
*> linalg_from_list data=`数据`*
完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_from_list(data=`数据`))*。
3. `名`
*> linalg_symbol name=`名` rows=`行` cols=`列`*
完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_symbol(name=`名`, rows=`行`, cols=`列`))*。
4. `阶`
*> linalg_eye n=`阶`*
完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_eye(n=`阶`))*。
5. `行`
*> linalg_zeros rows=`行` cols=`列`*
完成后返回*[矩阵值(_type=矩阵)。优先中缀 A + B / A * B,或 A.转置 。](linalg_zeros(rows=`行`, cols=`列`))*。
6. *
> print text=ext/linalg: 矩阵需要 名= / 数据= / 公式= / 阶= / 行=
*None*
这里**[输出本步已准备的消息](print(text="ext/linalg: 矩阵需要", 名="/", 数据="/", 公式="/", 阶="/", 行=""))**。
完成后返回*None*。
## 转置
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。 |
转置。
*> linalg_transpose expr=`self`*
完成后返回*[将当前输入交给 linalg_transpose,保留同源能力的返回值和失败语义。](linalg_transpose(expr=`self`))*。
## 转置文本
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 转置后输出 ASCII(默认化简)。适合讲义恒等式验收。 |
转置后输出 ASCII(默认化简)。适合讲义恒等式验收。
**`转` = > linalg_transpose expr=`self`**
*> linalg_ascii expr=`转` raw=False*
得到**`转` = [转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_transpose(expr=`self`))**。
完成后返回*[转置后输出 ASCII(默认化简)。适合讲义恒等式验收。](linalg_ascii(expr=`转`, raw=False))*。
## 加
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵 / 表达式加法。 |
这里使用`右`。
矩阵 / 表达式加法。
*> linalg_add a=`self` b=`右`*
完成后返回*[矩阵 / 表达式加法。](linalg_add(a=`self`, b=`右`))*。
## 减
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵 / 表达式减法。 |
这里使用`右`。
矩阵 / 表达式减法。
*> linalg_sub a=`self` b=`右`*
完成后返回*[矩阵 / 表达式减法。](linalg_sub(a=`self`, b=`右`))*。
## 乘
+ `右`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 右 | any | 必填 | 运算右侧的矩阵、表达式或方程右端 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 矩阵 / 表达式乘法。 |
这里使用`右`。
矩阵 / 表达式乘法。
*> linalg_mul a=`self` b=`右`*
完成后返回*[矩阵 / 表达式乘法。](linalg_mul(a=`self`, b=`右`))*。
## 逆
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 求逆。 |
求逆。
*> linalg_inv expr=`self`*
完成后返回*[求逆。](linalg_inv(expr=`self`))*。
## 化简
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 化简矩阵表达式。 |
化简矩阵表达式。
*> linalg_simplify expr=`self`*
完成后返回*[化简矩阵表达式。](linalg_simplify(expr=`self`))*。
## 文本
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | ASCII 展示。 |
ASCII 展示。
*> linalg_ascii expr=`self` raw=False*
完成后返回*[ASCII 展示。](linalg_ascii(expr=`self`, raw=False))*。
## 乳胶
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | LaTeX 展示。 |
LaTeX 展示。
*> linalg_latex expr=`self` raw=False*
完成后返回*[LaTeX 展示。](linalg_latex(expr=`self`, raw=False))*。
## 求值
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 求成显式矩阵。 |
这里使用`原始`=False。
求成显式矩阵。
*> linalg_explicit expr=`self` raw=`原始`*
完成后返回*[求成显式矩阵。](linalg_explicit(expr=`self`, raw=`原始`))*。
## 行列式
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。 |
行列式。
*> linalg_det expr=`self`*
完成后返回*[将当前输入交给 linalg_det,保留同源能力的返回值和失败语义。](linalg_det(expr=`self`))*。
## 迹
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。 |
迹。
*> linalg_trace expr=`self`*
完成后返回*[将当前输入交给 linalg_trace,保留同源能力的返回值和失败语义。](linalg_trace(expr=`self`))*。
## 展示
+ `路径`=None
+ `原始`=False
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 授权根目录内的文件路径 |
| 原始 | any | False | 渲染时是否保留未化简表达式树 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 展示 / 导出表达式。 |
这里使用`路径`=None、`原始`=False。
展示 / 导出表达式。
*> linalg_show expr=`self` path=`路径` raw=`原始`*
完成后返回*[展示 / 导出表达式。](linalg_show(expr=`self`, path=`路径`, raw=`原始`))*。
## 单位
+ `阶`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 阶 | any | 必填 | 方阵阶数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 对比特施加单位门 / 单位矩阵。 |
这里使用`阶`。
对比特施加单位门 / 单位矩阵。
*> linalg_eye n=`阶`*
完成后返回*[对比特施加单位门 / 单位矩阵。](linalg_eye(n=`阶`))*。
## 零阵
+ `行`
+ `列`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 行 | any | 必填 | 矩阵行数 |
| 列 | any | 必填 | 矩阵列数 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 零矩阵。 |
这里使用`行`、`列`。
零矩阵。
*> linalg_zeros rows=`行` cols=`列`*
完成后返回*[零矩阵。](linalg_zeros(rows=`行`, cols=`列`))*。
## 自列表
+ `数据`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 数据 | any | 必填 | 交给本操作处理的结构化数据 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 由嵌套列表构造矩阵。 |
这里使用`数据`。
由嵌套列表构造矩阵。
*> linalg_from_list data=`数据`*
完成后返回*[由嵌套列表构造矩阵。](linalg_from_list(data=`数据`))*。
## 自公式
+ `公式`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 公式 | any | 必填 | 原生矩阵解析器接受的符号公式 |
| 返回 | 类型 | 说明 |
|---|---|---|
| 结果 | any | 由公式文本构造矩阵。 |
这里使用`公式`。
由公式文本构造矩阵。
*> linalg_from_formula formula=`公式`*
完成后返回*[由公式文本构造矩阵。](linalg_from_formula(formula=`公式`))*。
+26 -9
View File
@@ -7,20 +7,37 @@ import:
sys: lib/sys.mq.md
---
This file constructs the application Result record only; it does not implement an HTTP transport. For real HTTP requests, response limits and downloads, import lib/net.mq.md. The [network entry](index.mq.md) distinguishes pure URL transformations from native WebSocket exchanges. Keep these responsibilities explicit when extending the package so a readable tool name never implies a missing capability.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/net: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
## result
+ `ok`
+ `value`=None
+ `error`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| ok | any | required | Whether this application-level operation succeeded |
| value | any | None | Value supplied to this operation; immutable transformations return a new value |
| error | any | None | Structured failure information supplied by the caller |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Unified Result map `{ok, value, error}`. |
Use `ok`, `value`=None, `error`=None as the inputs for this operation.
Unified Result map `{ok, value, error}`.
@@ -30,4 +47,4 @@ Unified Result map `{ok, value, error}`.
|----|-------|-------|
| `ok` | `value` | `error` |
*out*
Return *out*.
+62
View File
@@ -0,0 +1,62 @@
---
markup: occlusion
title: Network resources — URL data and WebSocket exchanges
import:
url_api: ext/net/url.mq.md
socket_api: ext/net/websocket.mq.md
---
This package provides [URL encoding](url.mq.md), the small [HTTP result constructor](http.mq.md),
and a native [WebSocket request/response resource](websocket.mq.md). For HTTP clients with
status, timeout, response limits and downloads, read the standard library net.mq.md directly.
The HTTP leaf here constructs a result record; its name does not imply an implemented HTTP client.
URL encoding is pure and needs no plugin. This command is ready to run from the repository root:
```sh
marqdo call ext/net/index.mq.md encode 'text="Marqdo notes/one"' --json
```
WebSocket exchanges need the native web plugin and an explicitly chosen server. Build the plugin
with scripts/build-web-plugin.sh, then supply a controlled endpoint to exchange. No example opens
a public socket implicitly. The resource closes after one bounded exchange; it is not a persistent
subscription API. Read the returned ok/error as well as the reply data before using the outcome.
Develop URL transformations by composing the public standard library; native transport belongs in
the web plugin. Preserve timeout units, byte/reply caps and close behavior. Add controlled local
server tests for transport failures and timeouts instead of treating an empty reply as success.
## encode
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| text | text | required | Text component to percent-encode; this does not fetch a URL |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | text | Encoded URL component returned by the public encoding helper |
The input `text` is content for an encoded component, not an already assembled URL to navigate.
Keeping this transformation separate makes it possible to build request data without network
permission. We return *[Percent-encode the selected component](url_api.encode(text=`text`))*
so the caller can place it in the intended path or query according to its own URL structure.
## exchange
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | text | required | Explicit ws/wss endpoint controlled by the caller |
| message | text | "" | Single outgoing text message |
| timeout_sec | number | 30 | Positive exchange timeout in seconds |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Native exchange result; failures carry ok=false/error instead of an empty successful reply |
The caller supplies `url`, optionally `message`="" and `timeout_sec`=30. This tool performs a
real exchange, so it needs plugin permission and an available endpoint. The native leaf caps
replies and frame sizes and closes the connection before returning; it does not retry a send.
We create **socket = [Configure a bounded WebSocket receiver](socket_api.ws(timeout_sec=`timeout_sec`))**,
then return *[Send the message and collect the bounded reply](> `socket`.connect url=`url` message=`message` )*.
Inspect the actual result before deciding whether a follow-up request is appropriate.
+16 -3
View File
@@ -6,7 +6,20 @@ import:
net: lib/net.mq.md
---
## encode
+ `text`
Use this leaf to encode data for a URL component, not to fetch or validate a remote service. The [network entry](index.mq.md) provides a directly runnable encoding example. Whole URLs, path components and query values have different escaping responsibilities; pass the intended component and let the caller assemble the final URL. Prefer composing lib/url.mq.md when adding pure transformations.
*> net.url_encode text=`text`*
## encode
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| text | any | required | Text supplied to the transformation or adapter |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Percent-encode the supplied text using the public standard library URL helper. |
Use `text` as the inputs for this operation.
Percent-encode the supplied text using the public standard library URL helper.
Return *[Url encode](net.url_encode(text=`text`))*.
+40 -13
View File
@@ -8,36 +8,63 @@ import:
table: lib/table.mq.md
---
This resource performs one bounded native WebSocket exchange and closes it. The [network entry](index.mq.md) shows the input contract and the distinction from pure URL encoding. Configure a controlled ws/wss endpoint and inspect ok/error, timeout and reply data before acting. New transport behavior belongs in the web plugin, with local tests for failed connections and oversized replies; this resource is not a persistent subscription service.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/net: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/net: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# ws
+ `timeout_sec`=30
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| timeout_sec | any | 30 | Request/response timeout in seconds |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | WebSocket client helper. |
Use `timeout_sec`=30 as the inputs for this operation.
WebSocket client helper.
> _load
We **[Load the native plugin required by this operation](_load())**.
`out` =
| timeout_sec | _type |
|-------------|-------|
| `timeout_sec` | ws |
*out*
Return *out*.
## connect
+ `url`
+ `message`=""
+ `headers`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | required | Resource connection URL; scheme selects the documented backend |
| message | any | "" | Outgoing WebSocket or application message |
| headers | any | None | HTTP request header record or None |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply. |
Use `url`, `message`="", `headers`=None as the inputs for this operation.
Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply.
**timeout = [timeout_sec](access(self, "timeout_sec"))**
*> web_ws_connect url=`url` message=`message` headers=`headers` timeout_sec=`timeout`*
We retain **`timeout` = [Read timeout_sec field](access(`self`, "timeout_sec"))**.
Return *[Single request–response: connect to url, send message, collect up to 256 server text replies (each up to 1 MiB), close](web_ws_connect(url=`url`, message=`message`, headers=`headers`, timeout_sec=`timeout`))*.
+9 -9
View File
@@ -30,6 +30,10 @@ and tests/call_cli.rs before returning to [circuit](../circuit/index.mq.md).
## load
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | null after a successful load |
Locate the ABI v2 quantum shared library through plugin.native_path, then
plugin.load it. If the library is missing, print a short install hint and exit
non-zero so CI and agents fail loudly. After a successful load, later quantum
@@ -39,14 +43,10 @@ start of each tool that needs the simulator.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | null after a successful load |
**p = > plugin.native_path name="quantum"**
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="quantum"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum)
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
File diff suppressed because it is too large. Load diff
+97 -83
View File
@@ -46,142 +46,156 @@ independent matrices in tests/ext/quantum-linalg-smoke.mq.md.
## from_state
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| state | any | required | pure state or circuit |
| 返回 | 类型 | 说明 |
|------|------|------|
| state | any | pure state or circuit |
| result | any | density handle |
Use `state` as the inputs for this operation.
Form rho as the outer product of a pure `state` (or the ideal state of a
circuit). Use this when you trust the pure-state picture and want mixed-state
tools without writing a matrix by hand.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Form rho as the outer product of a pure state (or the ideal state of a circuit)](quantum_density_from_state(state=`state`))*.
## from_matrix
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| matrix | any | required | Hermitian matrix |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | density handle |
> cap.load
*> quantum_density_from_state state=`state`*
## from_matrix
| 参数 | 类型 | 说明 |
|------|------|------|
| matrix | any | Hermitian matrix |
Use `matrix` as the inputs for this operation.
Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the
lecture so the matrix on the page is the matrix in the simulator. Size is
limited by the plugin.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | density handle |
> cap.load
*> quantum_density_from_matrix matrix=`matrix`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Build rho from an explicit Hermitian matrix](quantum_density_from_matrix(matrix=`matrix`))*.
## purity
| 参数 | 类型 | 说明 |
|------|------|------|
| density | any | density operator |
Compute the trace of rho squared for `density`. Values near one mean nearly
pure; lower values mean classical mixing or traced-out entanglement.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| density | any | required | density operator |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | purity |
> cap.load
*> quantum_density_purity density=`density`*
Use `density` as the inputs for this operation.
Compute the trace of rho squared for `density`. Values near one mean nearly
pure; lower values mean classical mixing or traced-out entanglement.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Compute the trace of rho squared for density. Values near one mean nearly pure; lower values mean classical mixing or traced-out entanglement.](quantum_density_purity(density=`density`))*.
## partial_trace
| 参数 | 类型 | 说明 |
|------|------|------|
| density | any | joint density |
| keep | any | qubit index list to keep |
Keep listed qubits in `keep` and trace out the rest of `density`. Indices use
LSB equals zero. The result is generally mixed even when the joint state was
pure.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| keep | any | required | qubit index list to keep |
| density | any | required | joint density |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | reduced density |
> cap.load
*> quantum_density_partial_trace density=`density` keep=`keep`*
Use `keep`, `density` as the inputs for this operation.
Keep listed qubits in `keep` and trace out the rest of `density`. Indices use
LSB equals zero. The result is generally mixed even when the joint state was
pure.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Keep listed qubits in keep and trace out the rest of density](quantum_density_partial_trace(density=`density`, keep=`keep`))*.
## expect
| 参数 | 类型 | 说明 |
|------|------|------|
| density | any | density operator |
| obs | any | Pauli string or matrix |
Expectation of observable `obs` on `density`. Pauli strings use left equals
high bit. Pass a matrix when the observable is not a Pauli product.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| obs | any | required | Pauli string or matrix |
| density | any | required | density operator |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | expectation value |
> cap.load
*> quantum_density_expect density=`density` obs=`obs`*
Use `obs`, `density` as the inputs for this operation.
Expectation of observable `obs` on `density`. Pauli strings use left equals
high bit. Pass a matrix when the observable is not a Pauli product.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Expectation of observable obs on density. Pauli strings use left equals high bit. Pass a matrix when the observable is not a Pauli product.](quantum_density_expect(density=`density`, obs=`obs`))*.
## eig
| 参数 | 类型 | 说明 |
|------|------|------|
| density | any | Hermitian density |
Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a
lecture needs the eigenbasis of rho.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| density | any | required | Hermitian density |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | eigenvalues and eigenvectors |
> cap.load
*> quantum_density_eig density=`density`*
Use `density` as the inputs for this operation.
Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a
lecture needs the eigenbasis of rho.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Hermitian spectrum of density as eigenvalues and eigenvectors. Useful when a lecture needs the eigenbasis of rho.](quantum_density_eig(density=`density`))*.
## matrix
| 参数 | 类型 | 说明 |
|------|------|------|
| density | any | Density handle / 密度句柄 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| density | any | required | Density handle / 密度句柄 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Nested complex entries with re and im |
Use `density` as the inputs for this operation.
Export the explicit nested complex matrix of `density`. Reading entries does not
change the density operator. Use the exported entries for an independent trace
check or further linear algebra; the caller remains responsible for physicality.
> cap.load
*> quantum_density_matrix density=`density`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Export the explicit nested complex matrix of density](quantum_density_matrix(density=`density`))*.
# density
| 参数 | 类型 | 说明 |
|------|------|------|
| state | any | Default None |
| matrix | any | Default None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| state | any | None | Default None |
| matrix | any | None | Default None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Returned value |
Inputs: `state`=None, `matrix`=None (input).
Use `state`=None, `matrix`=None as the inputs for this operation.
Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=. Density operations support at most six qubits. Pure and mixed states share this object surface for purity, partial trace, and expectation.
> cap.load
We **[Load the native plugin required by this operation](cap.load())**.
1. `matrix`
*> quantum_density_from_matrix matrix=`matrix`*
Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_matrix(matrix=`matrix`))*.
2. *
*> quantum_density_from_state state=`state`*
Return *[Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=](quantum_density_from_state(state=`state`))*.
## matrix
@@ -191,7 +205,7 @@ Construct a density operator from a pure state or circuit (state=) or from an ex
Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package.
*> quantum_density_matrix density=`self`*
Return *[Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package](quantum_density_matrix(density=`self`))*.
## purity
@@ -201,23 +215,23 @@ Return the explicit matrix of this density operator so authors can inspect entri
Compute Tr(ρ²). Values near one mean a pure state; mixed states are strictly less than one. Use this as a quick entanglement or decoherence check after a partial trace.
*> quantum_density_purity density=`self`*
Return *[Compute Tr(ρ²)](quantum_density_purity(density=`self`))*.
## partial_trace
| 参数 | 类型 | 说明 |
|------|------|------|
| keep | any | Required |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| keep | any | required | Required |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Density operator handle |
Inputs: `keep` (input).
Use `keep` as the inputs for this operation.
Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks.
*> quantum_density_partial_trace density=`self` keep=`keep`*
Return *[Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks.](quantum_density_partial_trace(density=`self`, keep=`keep`))*.
## eig
@@ -227,37 +241,37 @@ Trace out every qubit except those listed in keep (LSB index 0). Returns the red
Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors. Handy for lecture plots and for verifying that a constructed rho is physical.
*> quantum_density_eig density=`self`*
Return *[Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors](quantum_density_eig(density=`self`))*.
## expect
| 参数 | 类型 | 说明 |
|------|------|------|
| obs | any | Required |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| obs | any | required | Required |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | Scalar observation |
Inputs: `obs` (input).
Use `obs` as the inputs for this operation.
Expectation value of observable obs on this density. obs may be a Pauli string with the left end as the high bit, or an explicit matrix matching the density dimension.
*> quantum_density_expect density=`self` obs=`obs`*
Return *[Expectation value of observable obs on this density](quantum_density_expect(density=`self`, obs=`obs`))*.
## draw
| 参数 | 类型 | 说明 |
|------|------|------|
| path | any | Default None |
| kind | any | Default hinton |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | None | Default None |
| kind | any | "hinton" | Default hinton |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg with kind and svg |
Inputs: `path`=None, `kind`="hinton" (input).
Use `path`=None, `kind`="hinton" as the inputs for this operation.
Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density. Optional path writes SVG; kind selects which visual metaphor the lecture uses.
*> quantum_density_draw density=`self` path=`path` kind=`kind`*
Return *[Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density](quantum_density_draw(density=`self`, path=`path`, kind=`kind`))*.
+86 -77
View File
@@ -45,6 +45,10 @@ which binds the Hadamard formula directly into the author gate constructor.
## hadamard
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Hadamard gate handle |
The Hadamard gate creates equal superposition from computational basis states.
Its matrix in the computational basis is one over square-root two times the
matrix with ones on the first row and one then minus one on the second row.
@@ -53,43 +57,43 @@ equal minus combination. This tool returns a named gate handle for later apply.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Hadamard gate handle |
> cap.load
*> quantum_gate_new name="H" theta=None matrix=None*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[The Hadamard gate creates equal superposition from computational basis states](quantum_gate_new(name="H", theta=None, matrix=None))*.
## pauli_x
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Pauli X handle |
Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and
ket-one. Use it when a lecture needs an explicit NOT on the computational basis.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Pauli X handle |
> cap.load
*> quantum_gate_new name="X" theta=None matrix=None*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and ket-one](quantum_gate_new(name="X", theta=None, matrix=None))*.
## pauli_z
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Pauli Z handle |
Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone.
Its diagonal matrix is the standard computational-basis Z.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Pauli Z handle |
> cap.load
*> quantum_gate_new name="Z" theta=None matrix=None*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone](quantum_gate_new(name="Z", theta=None, matrix=None))*.
## cnot
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | CNOT gate handle |
The controlled-NOT on two qubits flips the target when the control is ket-one.
Wire order and bit-endianness follow the package convention where qubit 0 is the
rightmost label bit. Prefer applying via circuit tools with explicit control and
@@ -97,103 +101,108 @@ target indices when building lectures step by step.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | CNOT gate handle |
> cap.load
*> quantum_gate_new name="CX" theta=None matrix=None*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[The controlled-NOT on two qubits flips the target when the control is ket-one](quantum_gate_new(name="CX", theta=None, matrix=None))*.
## custom
| 参数 | 类型 | 说明 |
|------|------|------|
| matrix | any | unitary matrix formula or list |
| name | text | optional label defaulting to U |
Build a gate from an explicit unitary given as `matrix`. Authors usually bind a
formula matrix first, then pass that binding. Optional label `name`="U" marks
drawings when the caller omits a name.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| matrix | any | required | unitary matrix formula or list |
| name | text | "U" | optional label defaulting to U |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | custom gate handle |
> cap.load
*> quantum_gate_new name=`name` theta=None matrix=`matrix`*
Use `matrix`, `name`="U" as the inputs for this operation.
Build a gate from an explicit unitary given as `matrix`. Authors usually bind a
formula matrix first, then pass that binding. Optional label `name`="U" marks
drawings when the caller omits a name.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Build a gate from an explicit unitary given as matrix](quantum_gate_new(name=`name`, theta=None, matrix=`matrix`))*.
## matches
| 参数 | 类型 | 说明 |
|------|------|------|
| gate | any | gate handle to test |
| matrix | any | expected unitary |
| tol | number | absolute tolerance |
Teaching check: does `gate` match expected `matrix` within absolute tolerance
`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator
cannot drift apart.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| gate | any | required | gate handle to test |
| matrix | any | required | expected unitary |
| tol | number | 0.000000001 | absolute tolerance |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | bool | True when matrices match |
> cap.load
*> quantum_gate_matches_matrix gate=`gate` matrix=`matrix` tol=`tol`*
Use `gate`, `matrix`, `tol`=0.000000001 as the inputs for this operation.
Teaching check: does `gate` match expected `matrix` within absolute tolerance
`tol`=0.000000001 ? Use after defining a formula so the lecture and the simulator
cannot drift apart.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Teaching check: does gate match expected matrix within absolute tolerance cannot drift apart.](quantum_gate_matches_matrix(gate=`gate`, matrix=`matrix`, tol=`tol`))*.
## named
| 参数 | 类型 | 说明 |
|------|------|------|
| name | text | Built-in gate name |
| theta | any | Rotation angle or None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | text | "H" | Built-in gate name |
| theta | any | None | Rotation angle or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Gate handle for circuit.apply |
Use `name`="H", `theta`=None as the inputs for this operation.
Construct built-in `name`="H" with optional `theta`=None . Rx, Ry and Rz require
a numeric angle in radians. The returned gate can be passed to circuit.apply;
creating it never changes a circuit. Supported names are listed above.
> cap.load
*> quantum_gate_new name=`name` theta=`theta` matrix=None*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Construct built-in name="H" with optional theta=None ](quantum_gate_new(name=`name`, theta=`theta`, matrix=None))*.
## matrix
| 参数 | 类型 | 说明 |
|------|------|------|
| gate | any | Gate handle |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| gate | any | required | Gate handle |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Nested complex entries with re and im |
Use `gate` as the inputs for this operation.
Export the explicit unitary of `gate`. Each complex entry has re and im fields.
Use this to compare a formula with independent expected entries. Reading a gate
matrix neither modifies its handle nor applies the operator to any circuit.
> cap.load
*> quantum_gate_matrix gate=`gate`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Export the explicit unitary of gate](quantum_gate_matrix(gate=`gate`))*.
# gate
| 参数 | 类型 | 说明 |
|------|------|------|
| name | any | Default None |
| theta | number | Default None |
| matrix | any | Default None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | any | None | Default None |
| theta | number | None | Default None |
| matrix | any | None | Default None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Gate handle for circuit.apply |
Inputs: `name`=None, `theta`=None, `matrix`=None (input).
Use `name`=None, `theta`=None, `matrix`=None as the inputs for this operation.
Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence). Custom gates may set name= (default U). Authors and call-style tools share this object surface.
> cap.load
*> quantum_gate_new name=`name` theta=`theta` matrix=`matrix`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence)](quantum_gate_new(name=`name`, theta=`theta`, matrix=`matrix`))*.
## matrix
@@ -203,38 +212,38 @@ Named built-in gate (name=H) or a custom unitary defined by matrix= (nested list
Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula.
*> quantum_gate_matrix gate=`self`*
Return *[Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula.](quantum_gate_matrix(gate=`self`))*.
## matches_matrix
| 参数 | 类型 | 说明 |
|------|------|------|
| matrix | any | Required |
| tol | any | Default 0.000000001 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| matrix | any | required | Required |
| tol | any | 0.000000001 | Default 0.000000001 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | bool | Match within absolute tolerance |
Inputs: `matrix`, `tol`=0.000000001 (input).
Use `matrix`, `tol`=0.000000001 as the inputs for this operation.
Check whether this gate matches the given matrix within absolute tolerance tol. Typical after building a custom gate from a Markdown formula fence in a lecture notebook.
*> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`*
Return *[Check whether this gate matches the given matrix within absolute tolerance tol](quantum_gate_matches_matrix(gate=`self`, matrix=`matrix`, tol=`tol`))*.
## draw
| 参数 | 类型 | 说明 |
|------|------|------|
| path | any | Default None |
| kind | any | Default gate |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | any | None | Default None |
| kind | any | "gate" | Default gate |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg with kind and svg |
Inputs: `path`=None, `kind`="gate" (input).
Use `path`=None, `kind`="gate" as the inputs for this operation.
Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix). Optional path writes SVG to disk; plots also enter view/CLI through record_plot for the session.
*> quantum_gate_draw gate=`self` path=`path` kind=`kind`*
Return *[Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix)](quantum_gate_draw(gate=`self`, path=`path`, kind=`kind`))*.
+15 -14
View File
@@ -219,12 +219,12 @@ control the other. The resulting amplitudes correlate 00 with 11.
Return the circuit so a caller can apply another gate, attach noise, draw it
or independently test entanglement. Every step keeps the returned new value.
**qc = circuit.new qubits=2 steps=None**
We retain **`qc` = [New](circuit.new(qubits=2, steps=None))**.
Make two equal paths on the low wire, then propagate the path label to the other wire.
**qc = circuit.hadamard circuit=`qc` qubit=0**
*> circuit.cnot circuit=`qc` control=0 target=1*
We retain **`qc` = [Hadamard](circuit.hadamard(circuit=`qc`, qubit=0))**.
Return *[Cnot](circuit.cnot(circuit=`qc`, control=0, target=1))*.
## bell_phi_plus
@@ -237,8 +237,8 @@ returns only ideal probabilities. Expect equal weights on 00 and 11 and zero
elsewhere. Computational-basis correlation alone does not prove entanglement;
use bell_analysis for reduced purity, ZZ expectation and Schmidt evidence.
**qc = > bell_circuit**
*> simulate.probabilities circuit=`qc`*
We retain **`qc` = [Bell circuit](bell_circuit())**.
Return *[Probabilities](simulate.probabilities(circuit=`qc`))*.
## bell_analysis
@@ -253,23 +253,24 @@ or persistent session for the intermediate observations. Expect joint purity
one, reduced purity one-half, ZZ one and Schmidt entropy ln(2), within 1e-9.
All paths here describe ideal evolution rather than noisy trajectory averages.
**qc = > bell_circuit**
**probs = simulate.probabilities circuit=`qc`**
We retain **`qc` = [Bell circuit](bell_circuit())**.
We retain **`probs` = [Probabilities](simulate.probabilities(circuit=`qc`))**.
Build the joint density and compute purity. A pure joint state need not
have pure subsystems. Keep only the low wire and test the mixedness that
appears when information about the other wire is discarded.
**rho = density.from_state state=`qc`**
**whole = density.purity density=`rho`**
We retain **`rho` = [From state](density.from_state(state=`qc`))**.
We retain **`whole` = [Purity](density.purity(density=`rho`))**.
`kept` =
| qubit |
|-------|
| 0 |
**reduced = density.partial_trace density=`rho` keep=`kept`**
**local = density.purity density=`reduced`**
We retain **`reduced` = [Partial trace](density.partial_trace(density=`rho`, keep=`kept`))**.
We retain **`local` = [Purity](density.purity(density=`reduced`))**.
ZZ measures correlation and is not an entanglement witness by itself.
The Schmidt decomposition supplies pure-state coefficients and entropy.
@@ -277,8 +278,8 @@ Together these observations distinguish a Bell pure state from a classical
mixture with identical basis probabilities. Keep the measured values in the
return table rather than hiding them behind a pass label with an implicit threshold.
**correlation = density.expect density=`rho` obs="ZZ"**
**split = state.schmidt state=`qc` cut=1**
We retain **`correlation` = [Expect](density.expect(density=`rho`, obs="ZZ"))**.
We retain **`split` = [Schmidt](state.schmidt(state=`qc`, cut=1))**.
`report` =
@@ -286,4 +287,4 @@ return table rather than hiding them behind a pass label with an implicit thresh
|---------------|--------|----------------|----|---------|
| `probs` | `whole` | `local` | `correlation` | `split` |
*report*
Return *report*.
+55 -45
View File
@@ -51,85 +51,95 @@ For entanglement go to [state](../state/index.mq.md); for mixed states use
## simulate
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to evolve |
Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise
channels attached to the circuit are ignored here.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to evolve |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | amplitude list |
> cap.load
*> quantum_simulate circuit=`circuit`*
Use `circuit` as the inputs for this operation.
Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise
channels attached to the circuit are ignored here.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Return ideal state-vector amplitudes for circuit as re/im entries. Noise channels attached to the circuit are ignored here.](quantum_simulate(circuit=`circuit`))*.
## state
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to evolve |
Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state
object. Prefer this when later fidelity or density tools expect a state handle.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to evolve |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | ideal state |
> cap.load
*> quantum_state circuit=`circuit`*
Use `circuit` as the inputs for this operation.
Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state
object. Prefer this when later fidelity or density tools expect a state handle.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Same ideal amplitudes as simulate for circuit, packaged as the plugin state object. Prefer this when later fidelity or density tools expect a state handle.](quantum_state(circuit=`circuit`))*.
## probabilities
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to read |
Map basis label to probability for the ideal state of `circuit`. Labels use
qubit 0 as the rightmost bit. Noise is ignored.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to read |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | probability map |
> cap.load
*> quantum_probabilities circuit=`circuit`*
Use `circuit` as the inputs for this operation.
Map basis label to probability for the ideal state of `circuit`. Labels use
qubit 0 as the rightmost bit. Noise is ignored.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Map basis label to probability for the ideal state of circuit. Labels use qubit 0 as the rightmost bit. Noise is ignored.](quantum_probabilities(circuit=`circuit`))*.
## run
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to sample |
| shots | number | sample count |
| seed | number | RNG seed |
Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024
and `seed`=1 so replays are deterministic. Teaching noise is applied when set.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to sample |
| shots | number | 1024 | sample count |
| seed | number | 1 | RNG seed |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | counts or shot result |
> cap.load
*> quantum_run circuit=`circuit` shots=`shots` seed=`seed`*
Use `circuit`, `shots`=1024, `seed`=1 as the inputs for this operation.
Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024
and `seed`=1 so replays are deterministic. Teaching noise is applied when set.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Sample computational-basis outcomes from circuit. Defaults are shots=1024 and seed=1 so replays are deterministic. Teaching noise is applied when set.](quantum_run(circuit=`circuit`, shots=`shots`, seed=`seed`))*.
## noise
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to annotate |
| kind | text | noise family name |
| p | number | strength in the unit interval |
Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal
simulate and probability tools ignore it. Keep p small unless demonstrating
decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| kind | text | required | noise family name |
| p | number | required | strength in the unit interval |
| circuit | any | required | circuit to annotate |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | circuit with noise metadata |
> cap.load
*> quantum_noise circuit=`circuit` kind=`kind` p=`p`*
Use `kind`, `p`, `circuit` as the inputs for this operation.
Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal
simulate and probability tools ignore it. Keep p small unless demonstrating
decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Attach teaching noise of kind kind with strength p on circuit](quantum_noise(circuit=`circuit`, kind=`kind`, p=`p`))*.
+35 -28
View File
@@ -48,10 +48,16 @@ new implementation only with itself. Draw a single wire through
## kron
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | left factor state or matrix |
| b | any | required | right factor state or matrix |
| 返回 | 类型 | 说明 |
|------|------|------|
| a | any | left factor state or matrix |
| b | any | right factor state or matrix |
| result | any | tensor product |
Use `a`, `b` as the inputs for this operation.
The Kronecker product of `a` and `b` builds a larger space from two smaller
ones. For state vectors this writes product states; for matrices it enlarges
@@ -60,46 +66,47 @@ operators.
Pass handles the plugin already understands. For a pure-state product, convert circuits with simulate.state first. Matrix
factors take the operator branch; raw amplitude lists are not accepted as states.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | tensor product |
> cap.load
*> quantum_kron a=`a` b=`b`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[The Kronecker product of a and b builds a larger space from two smaller ones](quantum_kron(a=`a`, b=`b`))*.
## fidelity
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | required | first pure state or circuit |
| b | any | required | second pure state or circuit |
| 返回 | 类型 | 说明 |
|------|------|------|
| a | any | first pure state or circuit |
| b | any | second pure state or circuit |
| result | number | fidelity in the unit interval |
Use `a`, `b` as the inputs for this operation.
Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is
one when the states coincide and zero when they are orthogonal. You may pass a
circuit handle; the plugin uses the ideal simulated state. Teaching noise is
ignored.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | fidelity in the unit interval |
> cap.load
*> quantum_fidelity a=`a` b=`b`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Pure-state fidelity between a and b is the squared absolute overlap](quantum_fidelity(a=`a`, b=`b`))*.
## schmidt
| 参数 | 类型 | 说明 |
|------|------|------|
| state | any | pure state or circuit |
| cut | number | qubits in subsystem A low bits |
Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest
`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show
entanglement across the bipartition.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| state | any | required | pure state or circuit |
| cut | number | 1 | qubits in subsystem A low bits |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | singular values and factors |
> cap.load
*> quantum_schmidt state=`state` cut=`cut`*
Use `state`, `cut`=1 as the inputs for this operation.
Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest
`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show
entanglement across the bipartition.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Schmidt decomposition of state across a cut. Subsystem A owns the lowest entanglement across the bipartition.](quantum_schmidt(state=`state`, cut=`cut`))*.
+75 -62
View File
@@ -62,107 +62,124 @@ For input preparation follow [circuit](../circuit/index.mq.md),
## draw_circuit
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to render |
| theme | text | "dark" | dark light or bw |
| path | any | None | optional output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to render |
| path | any | optional output path or None |
| theme | text | dark light or bw |
| result | any | drawing result |
Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation.
Render `circuit` as gate rails and barriers. Choose `theme`="dark" by default;
light and bw preserve the same geometry. Optional `path`=None returns SVG
without a file. A nonempty path is available to author programs under run.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Render circuit as gate rails and barriers](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="circuit", qubit=0, theme=`theme`))*.
## draw_probs
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | circuit to render |
| theme | text | "dark" | dark light or bw |
| path | any | None | optional output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | drawing result |
> cap.load
*> quantum_draw_circuit circuit=`circuit` path=`path` kind="circuit" qubit=0 theme=`theme`*
## draw_probs
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit to render |
| path | any | optional output path or None |
| theme | text | dark light or bw |
Use `circuit`, `theme`="dark", `path`=None as the inputs for this operation.
Plot ideal basis probabilities of `circuit`. Default `theme`="dark" supports
light and bw alternatives. Optional `path`=None returns SVG without a file.
The bars ignore teaching noise, just like simulate.probabilities.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | drawing result |
> cap.load
*> quantum_draw_circuit circuit=`circuit` path=`path` kind="probs" qubit=0 theme=`theme`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Plot ideal basis probabilities of circuit](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="probs", qubit=0, theme=`theme`))*.
## draw_bloch
| 参数 | 类型 | 说明 |
|------|------|------|
| circuit | any | circuit source |
| path | any | optional output path or None |
| qubit | number | which wire |
| theme | text | dark light or bw |
Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default
`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit
circuit still produces one reduced wire picture, not a joint-state sphere.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| qubit | number | 0 | which wire |
| circuit | any | required | circuit source |
| theme | text | "dark" | dark light or bw |
| path | any | None | optional output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | drawing result |
> cap.load
*> quantum_draw_circuit circuit=`circuit` path=`path` kind="bloch" qubit=`qubit` theme=`theme`*
Use `qubit`=0, `circuit`, `theme`="dark", `path`=None as the inputs for this operation.
Show the reduced Bloch sphere of wire `qubit`=0 from `circuit`. Default
`theme`="dark"; optional `path`=None returns SVG without a file. A multi-qubit
circuit still produces one reduced wire picture, not a joint-state sphere.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Show the reduced Bloch sphere of wire qubit=0 from circuit. Default circuit still produces one reduced wire picture, not a joint-state sphere.](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind="bloch", qubit=`qubit`, theme=`theme`))*.
## draw_density
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| density | any | required | density operator |
| kind | text | "hinton" | hinton city density or paulivec |
| path | any | None | optional output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| density | any | density operator |
| path | any | optional output path or None |
| kind | text | hinton city density or paulivec |
| result | any | drawing result |
Use `density`, `kind`="hinton", `path`=None as the inputs for this operation.
Plot `density` using `kind`="hinton" by default. Alternatives are city,
density and paulivec. Optional `path`=None returns SVG without a file.
Use the density module to construct the mixed-state input before drawing.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Plot density using kind="hinton" by default](quantum_density_draw(density=`density`, path=`path`, kind=`kind`))*.
## draw_gate
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| gate | any | required | gate handle |
| kind | text | "gate" | gate or matrix |
| path | any | None | optional output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | drawing result |
> cap.load
*> quantum_density_draw density=`density` path=`path` kind=`kind`*
## draw_gate
| 参数 | 类型 | 说明 |
|------|------|------|
| gate | any | gate handle |
| path | any | optional output path or None |
| kind | text | gate or matrix |
Use `gate`, `kind`="gate", `path`=None as the inputs for this operation.
Plot `gate` using `kind`="gate" by default. Choose matrix for a complex-entry
heatmap. Optional `path`=None returns SVG without a file. This observes the
operator rather than applying it or changing any circuit.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | drawing result |
> cap.load
*> quantum_gate_draw gate=`gate` path=`path` kind=`kind`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Plot gate using kind="gate" by default](quantum_gate_draw(gate=`gate`, path=`path`, kind=`kind`))*.
## draw_state
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| circuit | any | required | Circuit evolved ideally |
| kind | text | "qsphere" | qsphere or multibloch |
| path | any | None | SVG output path or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| circuit | any | Circuit evolved ideally |
| kind | text | qsphere or multibloch |
| path | any | SVG output path or None |
| result | any | quantum_svg with kind and svg |
Use `circuit`, `kind`="qsphere", `path`=None as the inputs for this operation.
Observe the ideal state of `circuit` as a basis-amplitude/phase sphere or one
reduced Bloch sphere per wire. Default `kind`="qsphere"; use multibloch for the
@@ -171,9 +188,5 @@ local Bloch vectors alone cannot certify joint entanglement. Both advanced
figures currently use fixed styling; theme support remains Q8c work and is
not offered as a nonfunctional parameter here.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg with kind and svg |
> cap.load
*> quantum_draw_circuit circuit=`circuit` path=`path` kind=`kind` qubit=0 theme="dark"*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Observe the ideal state of circuit as a basis-amplitude/phase sphere or one reduced Bloch sphere per wire](quantum_draw_circuit(circuit=`circuit`, path=`path`, kind=`kind`, qubit=0, theme="dark"))*.
+73 -61
View File
@@ -55,116 +55,128 @@ record_plot 桥接。新增图类时同步本页和英文入口,别把文件
## 画电路
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 调用方提供的电路 |
| 主题 | text | "dark" | dark light 或 bw |
| 路径 | any | None | 可选输出路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 电路 |
| 路径 | any | 可选输出路径或 None |
| 主题 | text | dark light 或 bw |
| result | any | 绘图结果 |
这里使用`电路`、`主题`="dark"、`路径`=None。
把 `电路` 的门和屏障画成轨线。默认 `主题`="dark",也可选择 light 或 bw。
可选 `路径`=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。
主题选择只改变配色,不改变线路几何与计算含义。
这里**[调用 加载](能力.加载())**。
完成后返回*[把 电路 的门和屏障画成轨线。默认 主题="dark",也可选择 light 或 bw。 可选 路径=None 只返回 SVG,不写文件;非空路径供 run 下的作者程序使用。 主题选择只改变配色,不改变线路几何与计算含义。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="circuit", qubit=0, theme=`主题`))*。
## 画概率
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 调用方提供的电路 |
| 主题 | text | "dark" | dark light 或 bw |
| 路径 | any | None | 可选路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 绘图结果 |
> 能力.加载
*> quantum_draw_circuit circuit=`电路` path=`路径` kind="circuit" qubit=0 theme=`主题`*
## 画概率
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 电路 |
| 路径 | any | 可选路径或 None |
| 主题 | text | dark light 或 bw |
这里使用`电路`、`主题`="dark"、`路径`=None。
绘制 `电路` 的理想基矢概率条。默认 `主题`="dark",可改为 light 或 bw。
可选 `路径`=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致,
忽略已附加的教学噪声,不能用它替代含噪采样结果。
这里**[调用 加载](能力.加载())**。
完成后返回*[绘制 电路 的理想基矢概率条。默认 主题="dark",可改为 light 或 bw。 可选 路径=None 只返回 SVG,不写文件。图中权重与模拟模块的理想概率一致, 忽略已附加的教学噪声,不能用它替代含噪采样结果。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="probs", qubit=0, theme=`主题`))*。
## 画布洛赫
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 调用方提供的电路 |
| 比特 | number | 0 | 哪一根线 |
| 主题 | text | "dark" | dark light 或 bw |
| 路径 | any | None | 可选路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 绘图结果 |
> 能力.加载
*> quantum_draw_circuit circuit=`电路` path=`路径` kind="probs" qubit=0 theme=`主题`*
## 画布洛赫
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 电路 |
| 路径 | any | 可选路径或 None |
| 比特 | number | 哪一根线 |
| 主题 | text | dark light 或 bw |
这里使用`电路`、`比特`=0、`主题`="dark"、`路径`=None。
绘制 `电路` 上 `比特`=0 的约化布洛赫球。默认 `主题`="dark"。
可选 `路径`=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态,
不能把这张图解释为整个多比特纯态的完整表示。
这里**[调用 加载](能力.加载())**。
完成后返回*[绘制 电路 上 比特=0 的约化布洛赫球。默认 主题="dark"。 可选 路径=None 只返回 SVG,不写文件。多比特线路也只显示所选一条线的约化态, 不能把这张图解释为整个多比特纯态的完整表示。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind="bloch", qubit=`比特`, theme=`主题`))*。
## 画密度
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | 密度算符 |
| 种类 | text | "hinton" | hinton city density 或 paulivec |
| 路径 | any | None | 可选路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 绘图结果 |
> 能力.加载
*> quantum_draw_circuit circuit=`电路` path=`路径` kind="bloch" qubit=`比特` theme=`主题`*
## 画密度
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | 密度算符 |
| 路径 | any | 可选路径或 None |
| 种类 | text | hinton city density 或 paulivec |
这里使用`密度`、`种类`="hinton"、`路径`=None。
绘制 `密度`,默认 `种类`="hinton",也可选 city、density 或 paulivec。
可选 `路径`=None 只返回 SVG,不写文件。先在密度模块构造或约化输入,
再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。
这里**[调用 加载](能力.加载())**。
完成后返回*[绘制 密度,默认 种类="hinton",也可选 city、density 或 paulivec。 可选 路径=None 只返回 SVG,不写文件。先在密度模块构造或约化输入, 再按需要选择图类,本操作不改变密度矩阵或补做物理性认证。](quantum_density_draw(density=`密度`, path=`路径`, kind=`种类`))*。
## 画门
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 门 | any | 必填 | 门句柄 |
| 种类 | text | "gate" | gate 或 matrix |
| 路径 | any | None | 可选路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 绘图结果 |
> 能力.加载
*> quantum_density_draw density=`密度` path=`路径` kind=`种类`*
## 画门
| 参数 | 类型 | 说明 |
|------|------|------|
| 门 | any | 门句柄 |
| 路径 | any | 可选路径或 None |
| 种类 | text | gate 或 matrix |
这里使用`门`、`种类`="gate"、`路径`=None。
绘制 `门`,默认 `种类`="gate",选择 matrix 可观察复数矩阵热图。
可选 `路径`=None 只返回 SVG,不写文件。图形用于观察算符,
不会把门作用到任何电路,也不会改变算符的数值条目。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 绘图结果 |
> 能力.加载
*> quantum_gate_draw gate=`门` path=`路径` kind=`种类`*
这里**[调用 加载](能力.加载())**。
完成后返回*[绘制 门,默认 种类="gate",选择 matrix 可观察复数矩阵热图。 可选 路径=None 只返回 SVG,不写文件。图形用于观察算符, 不会把门作用到任何电路,也不会改变算符的数值条目。](quantum_gate_draw(gate=`门`, path=`路径`, kind=`种类`))*。
## 画态
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 源电路,作理想演化 |
| 种类 | text | "qsphere" | qsphere 或 multibloch |
| 路径 | any | None | SVG 输出路径或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 源电路,作理想演化 |
| 种类 | text | qsphere 或 multibloch |
| 路径 | any | SVG 输出路径或 None |
| result | any | quantum_svg,含 kind 和 svg |
这里使用`电路`、`种类`="qsphere"、`路径`=None。
从 `电路` 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。
默认 `种类`="qsphere",可改为 multibloch;默认 `路径`=None,不显式落盘。
qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。
这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg,含 kind 和 svg |
> 能力.加载
*> quantum_draw_circuit circuit=`电路` path=`路径` kind=`种类` qubit=0 theme="dark"*
这里**[调用 加载](能力.加载())**。
完成后返回*[从 电路 观察整体纯态的振幅/相位球,或每条线的约化布洛赫球。 默认 种类="qsphere",可改为 multibloch;默认 路径=None,不显式落盘。 qsphere 展示基矢振幅与相位,multibloch 展示各线约化态,不能由单线球图独自证明纠缠。 这两类高级态图当前使用固定配色,主题换肤仍属 Q8c 规划,不暴露无效主题参数。](quantum_draw_circuit(circuit=`电路`, path=`路径`, kind=`种类`, qubit=0, theme="dark"))*。
+95 -77
View File
@@ -37,132 +37,150 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect
## 从态
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 态 | any | 必填 | 纯态或电路 |
| 返回 | 类型 | 说明 |
|------|------|------|
| 态 | any | 纯态或电路 |
| result | any | 密度句柄 |
这里使用`态`。
由纯态或电路句柄 `态` 的理想态构造 rho。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 密度句柄 |
> 能力.加载
*> quantum_density_from_state state=`态`*
这里**[调用 加载](能力.加载())**。
完成后返回*[由纯态或电路句柄 态 的理想态构造 rho。](quantum_density_from_state(state=`态`))*。
## 从矩阵
| 参数 | 类型 | 说明 |
|------|------|------|
| 矩阵 | any | 厄米矩阵 |
由显式厄米 `矩阵` 构造 rho。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 矩阵 | any | 必填 | 厄米矩阵 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 密度句柄 |
> 能力.加载
*> quantum_density_from_matrix matrix=`矩阵`*
这里使用`矩阵`。
由显式厄米 `矩阵` 构造 rho。
这里**[调用 加载](能力.加载())**。
完成后返回*[由显式厄米 矩阵 构造 rho。](quantum_density_from_matrix(matrix=`矩阵`))*。
## 纯度
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | 密度算符 |
计算 `密度` 的 Tr(rho^2)。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | 密度算符 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | 纯度 |
> 能力.加载
*> quantum_density_purity density=`密度`*
这里使用`密度`。
计算 `密度` 的 Tr(rho^2)。
这里**[调用 加载](能力.加载())**。
完成后返回*[计算 密度 的 Tr(rho^2)。](quantum_density_purity(density=`密度`))*。
## 部分迹
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | 联合密度 |
| 保留 | any | 保留的比特下标列表 |
对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | 联合密度 |
| 保留 | any | 必填 | 保留的比特下标列表 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 约化密度 |
> 能力.加载
*> quantum_density_partial_trace density=`密度` keep=`保留`*
这里使用`密度`、`保留`。
对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。
这里**[调用 加载](能力.加载())**。
完成后返回*[对联合密度 密度 保留 保留 所列比特,对其余求迹。](quantum_density_partial_trace(density=`密度`, keep=`保留`))*。
## 期望
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | 密度算符 |
| 可观测量 | any | 泡利串或矩阵 |
`密度` 上可观测量 `可观测量` 的期望值。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | 密度算符 |
| 可观测量 | any | 必填 | 泡利串或矩阵 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | 期望值 |
> 能力.加载
*> quantum_density_expect density=`密度` obs=`可观测量`*
这里使用`密度`、`可观测量`。
将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。
`密度` 上可观测量 `可观测量` 的期望值。
这里**[调用 加载](能力.加载())**。
完成后返回*[将当前输入交给 quantum_density_expect,保留同源能力的返回值和失败语义。](quantum_density_expect(density=`密度`, obs=`可观测量`))*。
## 本征
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | 密度算符 |
`密度` 的厄米谱。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | 密度算符 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 本征值与本征矢 |
> 能力.加载
*> quantum_density_eig density=`密度`*
这里使用`密度`。
将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。
`密度` 的厄米谱。
这里**[调用 加载](能力.加载())**。
完成后返回*[将当前输入交给 quantum_density_eig,保留同源能力的返回值和失败语义。](quantum_density_eig(density=`密度`))*。
## 矩阵
| 参数 | 类型 | 说明 |
|------|------|------|
| 密度 | any | Density handle / 密度句柄 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 密度 | any | 必填 | Density handle / 密度句柄 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 复数矩阵条目,每项含 re 与 im |
这里使用`密度`。
导出 `密度` 的显式复数嵌套矩阵。观察条目不会改变密度算符,
可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。
> 能力.加载
*> quantum_density_matrix density=`密度`*
这里**[调用 加载](能力.加载())**。
完成后返回*[导出 密度 的显式复数嵌套矩阵。观察条目不会改变密度算符, 可用于独立计算迹或交给线性代数模块核对;物理性校验仍由调用者负责。](quantum_density_matrix(density=`密度`))*。
# 密度
| 参数 | 类型 | 说明 |
|------|------|------|
| 态 | any | 默认 None |
| 矩阵 | any | 默认 None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 态 | any | None | 默认 None |
| 矩阵 | any | None | 默认 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 返回结果 |
输入:`态`=None, `矩阵`=None。
这里使用`态`=None、`矩阵`=None。
由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。
> 能力.加载
这里**[调用 加载](能力.加载())**。
1. `矩阵`
*> quantum_density_from_matrix matrix=`矩阵`*
完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_matrix(matrix=`矩阵`))*。
2. *
*> quantum_density_from_state state=`态`*
完成后返回*[由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。](quantum_density_from_state(state=`态`))*。
## 矩阵
@@ -172,7 +190,7 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect
返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。
*> quantum_density_matrix density=`self`*
完成后返回*[返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。](quantum_density_matrix(density=`self`))*。
## 纯度
@@ -182,23 +200,23 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect
计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。
*> quantum_density_purity density=`self`*
完成后返回*[计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。](quantum_density_purity(density=`self`))*。
## 部分迹
| 参数 | 类型 | 说明 |
|------|------|------|
| 保留 | any | 必填 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 保留 | any | 必填 | 必填 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 密度算符句柄 |
输入:`保留`。
这里使用`保留`。
保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。
*> quantum_density_partial_trace density=`self` keep=`保留`*
完成后返回*[保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。](quantum_density_partial_trace(density=`self`, keep=`保留`))*。
## 本征
@@ -208,37 +226,37 @@ marqdo call ext/quantum/量子/密度/索引.mq.md 本征 '密度=$rho' --effect
计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。
*> quantum_density_eig density=`self`*
完成后返回*[计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。](quantum_density_eig(density=`self`))*。
## 期望
| 参数 | 类型 | 说明 |
|------|------|------|
| 可观测量 | any | 必填 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 可观测量 | any | 必填 | 必填 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | 标量观察值 |
输入:`可观测量`。
这里使用`可观测量`。
可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。
*> quantum_density_expect density=`self` obs=`可观测量`*
完成后返回*[可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。](quantum_density_expect(density=`self`, obs=`可观测量`))*。
## 绘图
| 参数 | 类型 | 说明 |
|------|------|------|
| 路径 | any | 默认 None |
| 种类 | any | 默认 hinton |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 默认 None |
| 种类 | any | "hinton" | 默认 hinton |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg,含 kind 与 svg |
输入:`路径`=None, `种类`="hinton"。
这里使用`路径`=None、`种类`="hinton"。
绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。
*> quantum_density_draw density=`self` path=`路径` kind=`种类`*
完成后返回*[绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。](quantum_density_draw(density=`self`, path=`路径`, kind=`种类`))*。
+31 -25
View File
@@ -40,49 +40,55 @@ entropy 单位为自然对数 nats,贝尔态为 ln(2),两个系数各约 1/
## 张量积
| 参数 | 类型 | 说明 |
|------|------|------|
| a | any | 左因子 |
| b | any | 右因子 |
将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | 必填 | 左因子 |
| b | any | 必填 | 右因子 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 张量积结果 |
> 能力.加载
*> quantum_kron a=`a` b=`b`*
这里使用`a`、`b`。
将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。
这里**[调用 加载](能力.加载())**。
完成后返回*[将 a 与 b 做张量积,得到更大空间上的态或算符。](quantum_kron(a=`a`, b=`b`))*。
## 保真度
| 参数 | 类型 | 说明 |
|------|------|------|
| a | any | 第一态或电路 |
| b | any | 第二态或电路 |
纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。
教学噪声忽略。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | any | 必填 | 第一态或电路 |
| b | any | 必填 | 第二态或电路 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | number | 保真度 |
> 能力.加载
*> quantum_fidelity a=`a` b=`b`*
这里使用`a`、`b`。
纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。
教学噪声忽略。
这里**[调用 加载](能力.加载())**。
完成后返回*[纯态 a 与 b 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 教学噪声忽略。](quantum_fidelity(a=`a`, b=`b`))*。
## 施密特分解
| 参数 | 类型 | 说明 |
|------|------|------|
| 态 | any | 纯态或电路 |
| 分割 | number | 子系统 A 比特数 |
对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 态 | any | 必填 | 纯态或电路 |
| 分割 | number | 1 | 子系统 A 比特数 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 施密特数据 |
> 能力.加载
*> quantum_schmidt state=`态` cut=`分割`*
这里使用`态`、`分割`=1。
对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。
这里**[调用 加载](能力.加载())**。
完成后返回*[对纯态或电路 态 做施密特分解。分割=1 表示子系统 A 的比特数(低位)。](quantum_schmidt(state=`态`, cut=`分割`))*。
+51 -39
View File
@@ -46,79 +46,91 @@ plugins/quantum/src/sim.rs,导出位于同目录 src/lib.rs。保持中英理
## 模拟
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 待演化电路 |
返回 `电路` 的理想态矢量振幅。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 待演化电路 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 振幅列表 |
> 能力.加载
*> quantum_simulate circuit=`电路`*
这里使用`电路`。
返回 `电路` 的理想态矢量振幅。
这里**[调用 加载](能力.加载())**。
完成后返回*[返回 电路 的理想态矢量振幅。](quantum_simulate(circuit=`电路`))*。
## 态
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 待演化电路 |
与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 待演化电路 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 理想态 |
> 能力.加载
*> quantum_state circuit=`电路`*
这里使用`电路`。
与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。
这里**[调用 加载](能力.加载())**。
完成后返回*[与模拟相同:取 电路 的理想振幅,打包为态对象,便于后续保真度或密度构造。](quantum_state(circuit=`电路`))*。
## 概率
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 待读取电路 |
`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 待读取电路 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 概率映射 |
> 能力.加载
*> quantum_probabilities circuit=`电路`*
这里使用`电路`。
将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。
`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。
这里**[调用 加载](能力.加载())**。
完成后返回*[将当前输入交给 quantum_probabilities,保留同源能力的返回值和失败语义。](quantum_probabilities(circuit=`电路`))*。
## 运行
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 待采样电路 |
| 次数 | number | 采样次数 |
| 种子 | number | 随机种子 |
对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 待采样电路 |
| 次数 | number | 1024 | 采样次数 |
| 种子 | number | 1 | 随机种子 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 计数或采样结果 |
> 能力.加载
*> quantum_run circuit=`电路` shots=`次数` seed=`种子`*
这里使用`电路`、`次数`=1024、`种子`=1。
对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。
这里**[调用 加载](能力.加载())**。
完成后返回*[对 电路 采样。默认 次数=1024、种子=1。若有教学噪声则轨迹含噪声。](quantum_run(circuit=`电路`, shots=`次数`, seed=`种子`))*。
## 噪声
| 参数 | 类型 | 说明 |
|------|------|------|
| 电路 | any | 电路 |
| 种类 | text | 噪声族名 |
| 强度 | number | 单位区间强度 |
在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 电路 | any | 必填 | 调用方提供的电路 |
| 种类 | text | 必填 | 噪声族名 |
| 强度 | number | 必填 | 单位区间强度 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 带噪声元数据的电路 |
> 能力.加载
*> quantum_noise circuit=`电路` kind=`种类` p=`强度`*
这里使用`电路`、`种类`、`强度`。
在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。
这里**[调用 加载](能力.加载())**。
完成后返回*[在 电路 上附着种类 种类、强度 强度 的教学噪声。理想概率工具忽略它。](quantum_noise(circuit=`电路`, kind=`种类`, p=`强度`))*。
File diff suppressed because it is too large. Load diff
+17 -14
View File
@@ -179,12 +179,12 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高
工具返回线路而非概率,便于继续施门、设置噪声或独立验证纠缠。
每一步接住新电路值,原值不被隐式修改。
**qc = 电路.新建 比特数=2 步骤=None**
得到**`qc` = [调用 新建](电路.新建(比特数=2, 步骤=None))**。
先让最低位具有两条等权路径,再把路径信息传播给第二条线。
**qc = 电路.哈达玛 电路=`qc` 比特=0**
*> 电路.控非 电路=`qc` 控制=0 目标=1*
得到**`qc` = [调用 哈达玛](电路.哈达玛(电路=`qc`, 比特=0))**。
完成后返回*[调用 控非](电路.控非(电路=`qc`, 控制=0, 目标=1))*。
## 贝尔态
@@ -196,8 +196,8 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高
00 和 11 各约一半,其余基矢为零;这是计算基关联,单靠概率还不能证明纠缠,
因此需要纠缠证据时继续调用本页纠缠分析,对照约化纯度与 ZZ 期望。
**qc = > 贝尔电路**
*> 模拟.概率 电路=`qc`*
得到**`qc` = [调用 贝尔电路](贝尔电路())**。
完成后返回*[调用 概率](模拟.概率(电路=`qc`))*。
## 纠缠分析
@@ -211,29 +211,32 @@ Bytecode。例子不能照抄运行就是公共接口缺陷,叙述比例再高
整体纯度应为 1,约化纯度应为 0.5,ZZ 应为 1,施密特熵为 ln(2)。
所有数值按 1e-9 容差核对;纯态概率与密度构造均使用理想演化。
**qc = > 贝尔电路**
**probs = 模拟.概率 电路=`qc`**
这里分析的是同一次制备的状态,避免分别重建电路导致比较对象不同。
得到**`qc` = [调用 贝尔电路](贝尔电路())**。
得到**`probs` = [调用 概率](模拟.概率(电路=`qc`))**。
先构造整体密度并计算纯度。整体纯不意味着每个局部也纯,
接着只保留最低位,检查丢弃另一个比特后出现的混合性。
**rho = 密度.从态 态=`qc`**
**whole = 密度.纯度 密度=`rho`**
得到**`rho` = [调用 从态](密度.从态(态=`qc`))**。
得到**`whole` = [调用 纯度](密度.纯度(密度=`rho`))**。
`kept` =
| 比特 |
|------|
| 0 |
**reduced = 密度.部分迹 密度=`rho` 保留=`kept`**
**local = 密度.纯度 密度=`reduced`**
得到**`reduced` = [调用 部分迹](密度.部分迹(密度=`rho`, 保留=`kept`))**。
得到**`local` = [调用 纯度](密度.纯度(密度=`reduced`))**。
ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯态两侧的
系数与熵;联合这些观察才能解释为何这是贝尔纯态而非经典概率混合。
返回表将各观察保留原值,便于调用者自行检查,而不是输出一个隐藏阈值的通过标签。
**correlation = 密度.期望 密度=`rho` 可观测量="ZZ"**
**split = 态.施密特分解 态=`qc` 分割=1**
得到**`correlation` = [调用 期望](密度.期望(密度=`rho`, 可观测量="ZZ"))**。
得到**`split` = [调用 施密特分解](态.施密特分解(态=`qc`, 分割=1))**。
`report` =
@@ -241,4 +244,4 @@ ZZ 测量关联,不是单独的纠缠判据。施密特分解独立给出纯
|---------------|--------|----------------|----|---------|
| `probs` | `whole` | `local` | `correlation` | `split` |
*report*
完成后返回*report*。
+9 -9
View File
@@ -26,20 +26,20 @@ marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --jso
## 加载
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 加载成功后为空 |
通过 plugin.native_path 找到 ABI v2 quantum 共享库,再 plugin.load。若缺失则打印
安装提示并以非零退出。成功后本进程内可用 quantum_* 符号。本包中只有这里应直接
接触 lib/plugin。领域模块在需要模拟器的工具开头调用加载。
本工具无参数。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 加载成功后为空 |
**p = > plugin.native_path name="quantum"**
得到**`p` = [定位已安装的原生插件](plugin.native_path(name="quantum"))**。
1. `p`
> plugin.load path=`p`
这里**[加载本操作依赖的原生插件](plugin.load(path=`p`))**。
2. *
> print text=ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum)
> sys.exit code=1
****
这里**[输出本步已准备的消息](print(text="ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum)"))**。
这里**[按指定退出码结束本次运行](sys.exit(code=1))**。
完成后返回*None*。
+81 -73
View File
@@ -38,140 +38,148 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects
## 哈达玛
哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。
本工具无参数。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 哈达玛门句柄 |
> 能力.加载
*> quantum_gate_new name="H" theta=None matrix=None*
## 泡利X
泡利 X 是比特翻转门。
哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。
本工具无参数。
这里**[调用 加载](能力.加载())**。
完成后返回*[哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 本工具无参数。](quantum_gate_new(name="H", theta=None, matrix=None))*。
## 泡利X
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 泡利 X 句柄 |
> 能力.加载
*> quantum_gate_new name="X" theta=None matrix=None*
## 泡利Z
泡利 Z 给 ket-one 乘上负号相位。
泡利 X 是比特翻转门。
本工具无参数。
这里**[调用 加载](能力.加载())**。
完成后返回*[泡利 X 是比特翻转门。 本工具无参数。](quantum_gate_new(name="X", theta=None, matrix=None))*。
## 泡利Z
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 泡利 Z 句柄 |
> 能力.加载
*> quantum_gate_new name="Z" theta=None matrix=None*
## 控非门
两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。
泡利 Z 给 ket-one 乘上负号相位。
本工具无参数。
这里**[调用 加载](能力.加载())**。
完成后返回*[泡利 Z 给 ket-one 乘上负号相位。 本工具无参数。](quantum_gate_new(name="Z", theta=None, matrix=None))*。
## 控非门
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | CNOT 门句柄 |
> 能力.加载
*> quantum_gate_new name="CX" theta=None matrix=None*
两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。
本工具无参数。
这里**[调用 加载](能力.加载())**。
完成后返回*[两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 本工具无参数。](quantum_gate_new(name="CX", theta=None, matrix=None))*。
## 自定义
| 参数 | 类型 | 说明 |
|------|------|------|
| 矩阵 | any | 酉矩阵公式或列表 |
| 名 | text | 可选标签,默认 U |
用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 矩阵 | any | 必填 | 酉矩阵公式或列表 |
| 名 | text | "U" | 可选标签,默认 U |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 自定义门句柄 |
> 能力.加载
*> quantum_gate_new name=`名` theta=None matrix=`矩阵`*
这里使用`矩阵`、`名`="U"。
用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。
这里**[调用 加载](能力.加载())**。
完成后返回*[用显式酉矩阵 矩阵 构造门。可选标签 名="U"。](quantum_gate_new(name=`名`, theta=None, matrix=`矩阵`))*。
## 匹配
| 参数 | 类型 | 说明 |
|------|------|------|
| 门 | any | 门句柄 |
| 矩阵 | any | 期望酉矩阵 |
| 容差 | number | 绝对容差 |
检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 门 | any | 必填 | 门句柄 |
| 容差 | number | 0.000000001 | 绝对容差 |
| 矩阵 | any | 必填 | 期望酉矩阵 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | bool | 匹配则为 True |
> 能力.加载
*> quantum_gate_matches_matrix gate=`门` matrix=`矩阵` tol=`容差`*
这里使用`门`、`容差`=0.000000001、`矩阵`。
检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。
这里**[调用 加载](能力.加载())**。
完成后返回*[检查 门 是否在容差 容差=0.000000001 内匹配 矩阵。](quantum_gate_matches_matrix(gate=`门`, matrix=`矩阵`, tol=`容差`))*。
## 具名
| 参数 | 类型 | 说明 |
|------|------|------|
| 名 | text | 内置门名 |
| 参数 | any | 旋转角或 None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 名 | text | "H" | 内置门名 |
| 参数 | any | None | 旋转角或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 可交给施加工具的门句柄 |
这里使用`名`="H"、`参数`=None。
构造内置门 `名`="H";可选 `参数`=None,Rx、Ry、Rz 必须给出弧度角。
返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。
> 能力.加载
*> quantum_gate_new name=`名` theta=`参数` matrix=None*
这里**[调用 加载](能力.加载())**。
完成后返回*[构造内置门 名="H";可选 参数=None,Rx、Ry、Rz 必须给出弧度角。 返回可交给电路施加的门句柄,创建过程不改变任何线路。支持名称见本页开篇表述。](quantum_gate_new(name=`名`, theta=`参数`, matrix=None))*。
## 矩阵
| 参数 | 类型 | 说明 |
|------|------|------|
| 门 | any | 门句柄 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 门 | any | 必填 | 门句柄 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 复数矩阵条目,每项含 re 与 im |
这里使用`门`。
导出 `门` 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较;
本工具仅观察算符,不改变句柄,也不把门应用到任何电路。
> 能力.加载
*> quantum_gate_matrix gate=`门`*
这里**[调用 加载](能力.加载())**。
完成后返回*[导出 门 的显式酉矩阵。每个元素含 re、im,可用于公式复核或独立矩阵比较; 本工具仅观察算符,不改变句柄,也不把门应用到任何电路。](quantum_gate_matrix(gate=`门`))*。
# 门
| 参数 | 类型 | 说明 |
|------|------|------|
| 名 | any | 默认 None |
| 参数 | number | 默认 None |
| 矩阵 | any | 默认 None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 名 | any | None | 默认 None |
| 参数 | number | None | 默认 None |
| 矩阵 | any | None | 默认 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 可交给施加工具的门句柄 |
输入:`名`=None, `参数`=None, `矩阵`=None。
这里使用`名`=None、`参数`=None、`矩阵`=None。
具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。
> 能力.加载
*> quantum_gate_new name=`名` theta=`参数` matrix=`矩阵`*
这里**[调用 加载](能力.加载())**。
完成后返回*[具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。](quantum_gate_new(name=`名`, theta=`参数`, matrix=`矩阵`))*。
## 矩阵
@@ -181,38 +189,38 @@ marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 '电路=$qc' --effects
返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。
*> quantum_gate_matrix gate=`self`*
完成后返回*[返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。](quantum_gate_matrix(gate=`self`))*。
## 匹配矩阵
| 参数 | 类型 | 说明 |
|------|------|------|
| 矩阵 | any | 必填 |
| 容差 | any | 默认 0.000000001 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 矩阵 | any | 必填 | 必填 |
| 容差 | any | 0.000000001 | 默认 0.000000001 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | bool | 容差内匹配 |
输入:`矩阵`, `容差`=0.000000001。
这里使用`矩阵`、`容差`=0.000000001。
检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。
*> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`*
完成后返回*[检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。](quantum_gate_matches_matrix(gate=`self`, matrix=`矩阵`, tol=`容差`))*。
## 绘图
| 参数 | 类型 | 说明 |
|------|------|------|
| 路径 | any | 默认 None |
| 种类 | any | 默认 gate |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路径 | any | None | 默认 None |
| 种类 | any | "gate" | 默认 gate |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | quantum_svg,含 kind 与 svg |
输入:`路径`=None, `种类`="gate"。
这里使用`路径`=None、`种类`="gate"。
绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。
*> quantum_gate_draw gate=`self` path=`路径` kind=`种类`*
完成后返回*[绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。](quantum_gate_draw(gate=`self`, path=`路径`, kind=`种类`))*。
+73 -21
View File
@@ -8,53 +8,105 @@ import:
table: lib/table.mq.md
---
Read [the security entry](index.mq.md) to distinguish credential/session operations, role checks and OIDC integration. This leaf owns the native authentication resource; endpoint metadata still controls route authorization. Prepare the native web plugin, keep secrets out of examples and logs, and verify both denied and accepted credentials before changing session behavior.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# auth
+ `users`
+ `session_ttl`=3600
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| users | any | required | Configured user store used by authentication |
| session_ttl | any | 3600 | Session lifetime in seconds |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead. |
Use `users`, `session_ttl`=3600 as the inputs for this operation.
Session/auth helper. Constructs a config object; `login` validates against the users table. To gate `/admin` on this app, use `app.auth users=…` instead.
> _load
*> web_auth_new users=`users` session_ttl=`session_ttl`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Session/auth helper. Constructs a config object; login validates against the users table. To gate /admin on this app, use app.auth users=… instead.](web_auth_new(users=`users`, session_ttl=`session_ttl`))*.
## login
+ `username`
+ `password`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| username | any | required | User name in the configured user store |
| password | any | required | Credential supplied for verification or hashing; do not log it |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`. |
Use `username`, `password` as the inputs for this operation.
Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`.
**users = [users](access(self, "users"))**
**ttl = [session_ttl](access(self, "session_ttl"))**
*> web_auth_login username=`username` password=`password` users=`users` session_ttl=`ttl`*
We retain **`users` = [Read users field](access(`self`, "users"))**.
We retain **`ttl` = [Read session_ttl field](access(`self`, "session_ttl"))**.
Return *[Validate credentials against the users table and create a session. Returns {ok, session_id, username, role}.](web_auth_login(username=`username`, password=`password`, users=`users`, session_ttl=`ttl`))*.
## check
+ `session_id`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| session_id | any | required | Session identifier returned by login |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Returns `{ok, username, role}` when the session is valid. |
Use `session_id` as the inputs for this operation.
Returns `{ok, username, role}` when the session is valid.
*> web_auth_check session_id=`session_id`*
Return *[Returns {ok, username, role} when the session is valid.](web_auth_check(session_id=`session_id`))*.
## logout
+ `session_id`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| session_id | any | required | Session identifier returned by login |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Destroy the session. |
Use `session_id` as the inputs for this operation.
Destroy the session.
*> web_auth_logout session_id=`session_id`*
Return *[Destroy the session.](web_auth_logout(session_id=`session_id`))*.
## hash_password
+ `password`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| password | any | required | Credential supplied for verification or hashing; do not log it |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically. |
Use `password` as the inputs for this operation.
Hash a plaintext password for storage in admin user tables (argon2id). Store the returned `hash` in the `password` column; login verifies automatically.
*> web_password_hash password=`password`*
Return *[Hash a plaintext password for storage in admin user tables (argon2id). Store the returned hash in the password column; login verifies automatically.](web_password_hash(password=`password`))*.
+48
View File
@@ -0,0 +1,48 @@
---
markup: occlusion
title: Security resources — authentication, roles and OIDC
import:
permissions_api: ext/security/rbac.mq.md
---
Use [auth](auth.mq.md) for credential/session operations, [rbac](rbac.mq.md) for role permissions,
and [OIDC](oidc.mq.md) for attaching an external identity provider to an existing web app.
Endpoint authorization remains explicit in the web artifact metadata; a script permission check
does not automatically protect an HTTP route.
The resources use the native web plugin. Build it with scripts/build-web-plugin.sh in this checkout.
This entry's deterministic permission check does not contact an identity provider or change users:
```sh
marqdo call ext/security/index.mq.md check_permission 'held="notes:read"' 'needed="notes:read"' --effects plugin --json
```
Constructors create receivers that are used by resource methods. The free function below makes
that pattern available to CLI callers without copying opaque object fields. For OIDC, configure
registered callback URLs and origin restrictions in oidc.mq.md; never copy production credentials
into a source example. Transport success and authorization success are distinct fields.
Develop native security policy in the existing web security implementation, then document the
public contract and exercise both allow and deny cases. Keep permission delimiters, wildcard
behavior, session lifetime and credential handling explicit. Use local fixtures for login and
OIDC tests; the reusable source must not require a live identity service merely to be inspected.
## check_permission
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| held | text | required | Comma-separated permissions held by the subject; wildcard follows the native RBAC policy |
| needed | text | required | Comma-separated required permissions interpreted by the documented RBAC checker |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | map | Native ok/allowed record; inspect allowed to decide authorization |
The inputs `held` and `needed` describe one explicit permission decision, not a role assignment
or a request to modify the user database. The native checker currently accepts any matching
required permission; held wildcard permits all. Use the leaf API when changing a role catalog.
The checker is an associated tool: it does not read self, so this workflow calls its definition
path directly rather than pretending it is an instance method. We return *[Evaluate this subject against the requested permission set](permissions_api.rbac.can(permissions=`held`, needed=`needed`))* .
The returned allowed field is the authorization decision; the outer CLI ok only reports whether
this function call completed. A denied decision remains a valid, observable result.
+35 -18
View File
@@ -7,28 +7,45 @@ import:
sys: lib/sys.mq.md
---
OIDC attaches provider configuration to an existing web application. Read [the security entry](index.mq.md) for the ownership boundaries before configuring a live identity provider. Registered callback URLs, origin checks and credentials require real deployment configuration; constructing a record alone does not validate a login flow. Keep provider failures distinct from permission decisions and exercise callbacks with controlled fixtures.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
## attach
+ `app`
+ `issuer`=None
+ `client_id`
+ `client_secret`
+ `redirect_uri`
+ `redirect_origins`=None
+ `scopes`="openid profile email"
+ `callback_path`=None
+ `authorize_url`=None
+ `token_url`=None
+ `userinfo_url`=None
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | required | Existing web application resource |
| issuer | any | None | OIDC issuer URL; None requires explicit provider endpoint configuration |
| client_id | any | required | Client identifier registered with the identity provider |
| client_secret | any | required | Client credential; supply through trusted runtime configuration |
| redirect_uri | any | required | Registered absolute callback URL or callback path |
| redirect_origins | any | None | Comma-separated callback origin allowlist when using a path callback |
| scopes | any | "openid profile email" | Space-separated identity-provider scopes |
| callback_path | any | None | Explicit callback route override or None for the implementation default |
| authorize_url | any | None | Authorization endpoint override |
| token_url | any | None | Token-exchange endpoint override |
| userinfo_url | any | None | User-info endpoint override |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | (`/oidc/callback`). Path mode resolves the absolute callback from the login request Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores it in the session so token exchange uses the same string. Optional `redirect_origins` is a comma-separated allowlist (`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. The IdP must still register every absolute callback URL that will be used. |
Use `app`, `issuer`=None, `client_id`, `client_secret`, `redirect_uri`, `redirect_origins`=None, `scopes`="openid profile email", `callback_path`=None, `authorize_url`=None, `token_url`=None, `userinfo_url`=None as the inputs for this operation.
`redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path
(`/oidc/callback`). Path mode resolves the absolute callback from the login request
@@ -39,5 +56,5 @@ Optional `redirect_origins` is a comma-separated allowlist
(`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match.
The IdP must still register every absolute callback URL that will be used.
> _load
*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` redirect_origins=`redirect_origins` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`*
We **[Load the native plugin required by this operation](_load())**.
Return *[(/oidc/callback)](web_app_oidc(app=`app`, issuer=`issuer`, client_id=`client_id`, client_secret=`client_secret`, redirect_uri=`redirect_uri`, redirect_origins=`redirect_origins`, scopes=`scopes`, callback_path=`callback_path`, authorize_url=`authorize_url`, token_url=`token_url`, userinfo_url=`userinfo_url`))*.
+72 -25
View File
@@ -8,56 +8,103 @@ import:
table: lib/table.mq.md
---
Role and permission data are explicit inputs to the native web checker. The [security entry](index.mq.md) executes allow and deny cases without an identity provider. The can tool is associated with rbac rather than a receiver method because it reads only its arguments. Held wildcard and any-match needed permissions follow the native policy; do not reinterpret that as an all-permissions check.
## _load
**p = > plugin.native_path name="web"**
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | No business value on completion; a missing native plugin reports the cause and exits this run. |
Resolve and load the native web plugin before resource operations; missing binaries stop this run.
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/security: native web plugin not found
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/security: native web plugin not found"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
# rbac
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests. |
Offline helpers for role ⊥ permission. Prefer `app.enable_rbac` + gates for HTTP; use these for scripts/tests.
## can
+ `permissions`
+ `needed`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| permissions | any | required | Comma-separated permission names held by the current role or subject |
| needed | any | required | Permission names required by the operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all. |
Use `permissions`, `needed` as the inputs for this operation.
Return `{ok, allowed}` — whether held permission CSV includes any of `needed` (CSV). Held `*` allows all.
> _load
*> web_rbac_can permissions=`permissions` needed=`needed`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Return {ok, allowed} — whether held permission CSV includes any of needed (CSV). Held * allows all.](web_rbac_can(permissions=`permissions`, needed=`needed`))*.
## assign_role
+ `url`
+ `username`
+ `role`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | required | Resource connection URL; scheme selects the documented backend |
| username | any | required | User name in the configured user store |
| role | any | required | Role name within the selected user store |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Bind `username` (in `web_users`) to role name. |
Use `url`, `username`, `role` as the inputs for this operation.
Bind `username` (in `web_users`) to role name.
> _load
*> web_rbac_assign_role url=`url` username=`username` role=`role`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Bind username (in web_users) to role name.](web_rbac_assign_role(url=`url`, username=`username`, role=`role`))*.
## create_role
+ `url`
+ `name`
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | required | Resource connection URL; scheme selects the documented backend |
| name | any | required | Name registered or looked up by this operation |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Create a non-system role; returns `{ok, id, name}`. |
Use `url`, `name` as the inputs for this operation.
Create a non-system role; returns `{ok, id, name}`.
> _load
*> web_rbac_create_role url=`url` name=`name`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Create a non-system role; returns {ok, id, name}.](web_rbac_create_role(url=`url`, name=`name`))*.
## set_role_permissions
+ `url`
+ `role`
+ `permissions`
+ `grantable`=""
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| url | any | required | Resource connection URL; scheme selects the documented backend |
| role | any | required | Role name within the selected user store |
| permissions | any | required | Comma-separated permission names held by the current role or subject |
| grantable | any | "" | Permission catalog limiting which permissions may be granted |
| 返回 | 类型 | 说明 |
|---|---|---|
| result | any | Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog. |
Use `url`, `role`, `permissions`, `grantable`="" as the inputs for this operation.
Replace permissions on a non-system role (CSV). `grantable` restricts grants (anti-escalation); empty = full catalog.
> _load
*> web_rbac_set_role_permissions url=`url` role=`role` permissions=`permissions` grantable=`grantable`*
We **[Load the native plugin required by this operation](_load())**.
Return *[Replace permissions on a non-system role (CSV). grantable restricts grants (anti-escalation); empty = full catalog.](web_rbac_set_role_permissions(url=`url`, role=`role`, permissions=`permissions`, grantable=`grantable`))*.
+9 -9
View File
@@ -22,6 +22,10 @@ Only this boundary imports lib/plugin, including through the Chinese facade.
## load
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | null after a successful load |
Locate the ABI v2 web shared library through plugin.native_path, then
plugin.load it. If the library is missing, print a short install hint and exit
non-zero so CI and agents fail loudly. After a successful load, later web star
@@ -31,14 +35,10 @@ of each tool that needs the native server or renderer.
This tool takes no parameters.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | null after a successful load |
**p = > plugin.native_path name="web"**
We retain **`p` = [Locate the installed native plugin](plugin.native_path(name="web"))**.
1. `p`
> plugin.load path=`p`
We **[Load the native plugin required by this operation](plugin.load(path=`p`))**.
2. *
> print text=ext/web: native web plugin not found (build plugins/web or marqdo ext add web)
> sys.exit code=1
****
We **[Print the prepared message](print(text="ext/web: native web plugin not found (build plugins/web or marqdo ext add web)"))**.
We **[End this run with the selected exit status](sys.exit(code=1))**.
Return *None*.
+46 -37
View File
@@ -24,71 +24,80 @@ browser bridge tests and matching Chinese entry points.
## embed
| 参数 | 类型 | 说明 |
|------|------|------|
| bridge | text | bridge script URL |
| wasm | text | wasm URL |
| source | text | optional source URL |
| boot | bool | auto boot |
HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults:
`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm",
`source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author
JS. Not a substitute for file-partitioned Document layout.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| bridge | text | "/static/marqdo-bridge.js" | bridge script URL |
| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL |
| source | text | "" | optional source URL |
| boot | bool | True | auto boot |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | HTML script tag |
Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation.
HTML snippet that loads the official browser Marqdo bridge (route C/D). Defaults:
`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm",
`source`="", `boot`=True . With boot and non-empty source, auto-mounts. No author
JS. Not a substitute for file-partitioned Document layout.
1. `boot`
1. `source` != ""
*"<script type=\"module\" src=\"" + bridge + "\" data-mq-wasm=\"" + wasm + "\" data-mq-source-url=\"" + source + "\"></script>"*
Return *"<script type=\"module\" src=\"" + bridge + "\" data-mq-wasm=\"" + wasm + "\" data-mq-source-url=\"" + source + "\"></script>"*.
2. *
*"<script type=\"module\" src=\"" + bridge + "\"></script>"*
Return *"<script type=\"module\" src=\"" + bridge + "\"></script>"*.
2. *
*"<script type=\"module\" src=\"" + bridge + "\" data-mq-no-boot=\"1\"></script>"*
Return *"<script type=\"module\" src=\"" + bridge + "\" data-mq-no-boot=\"1\"></script>"*.
## text_patch
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sel | text | required | CSS selector |
| text | text | required | text content |
| 返回 | 类型 | 说明 |
|------|------|------|
| sel | text | CSS selector |
| text | text | text content |
| result | any | effects map |
Use `sel`, `text` as the inputs for this operation.
Build a `set_text` effects map for selector `sel` with string `text`. Prefer
lib/browser in client .mq.md programs; this helper is for call-side sketches.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | effects map |
**`m` = > table.put in=None at=sel value=text**
*> table.put in=None at="set_text" value=m*
We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`text`))**.
Return *[Set the set_text field in the new record](table.put(in=None, at="set_text", value=`m`))*.
## dom_patch
| 参数 | 类型 | 说明 |
|------|------|------|
| sel | text | CSS selector |
| html | text | optional HTML |
| attrs | any | optional attrs map |
| remove | bool | remove node |
Build a `dom` effects map for selector `sel`. Optional `html`="", `attrs`=None,
`remove`=False . Prefer View/Markdown over raw html patches for page shells.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sel | text | required | CSS selector |
| html | text | "" | optional HTML |
| attrs | any | None | optional attrs map |
| remove | bool | False | remove node |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | effects map |
**`spec` = > table.put in=None at="html" value=html**
Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation.
Build a `dom` effects map for selector `sel`. Optional `html`="", `attrs`=None,
`remove`=False . Prefer View/Markdown over raw html patches for page shells.
We retain **`spec` = [Set the html field in the new record](table.put(in=None, at="html", value=`html`))**.
1. `attrs`
**`spec` = > table.put in=`spec` at="attrs" value=attrs**
We retain **`spec` = [Set the attrs field in the new record](table.put(in=`spec`, at="attrs", value=`attrs`))**.
2. *
**_ = 1**
1. `remove`
**`spec` = > table.put in=`spec` at="remove" value=True**
We retain **`spec` = [Set the remove field in the new record](table.put(in=`spec`, at="remove", value=True))**.
2. *
**_ = 1**
**`m` = > table.put in=None at=sel value=spec**
*> table.put in=None at="dom" value=m*
We retain **`m` = [Return the updated structured value](table.put(in=None, at=`sel`, value=`spec`))**.
Return *[Set the dom field in the new record](table.put(in=None, at="dom", value=`m`))*.
+31 -23
View File
@@ -32,50 +32,56 @@ Never put rendered HTML strings in parent value cells to simulate nesting.
## nodes
| 参数 | 类型 | 说明 |
|------|------|------|
| table | any | View table |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | View table |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Result |
| result | any | The supplied View table unchanged, preserving its original list or column-table shape |
Use `table` as the inputs for this operation.
Return View `table` unchanged. This preserves the existing identity helper for
column tables as well as record lists. Prefer @ record lists for reusable
components, because list composition can retain typed nested value cells.
*table*
Return *table*.
## merge
| 参数 | 类型 | 说明 |
|------|------|------|
| a | list | First node record list |
| b | list | Second node record list |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | list | required | First node record list |
| b | list | required | Second node record list |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | Ordered sibling rows |
Use `a`, `b` as the inputs for this operation.
Concatenate `a` and `b` without rendering or flattening child containers.
Both inputs must be lists of View rows, normally @ record tables. To place
two components side by side, concatenate their wrapped columns then use
layout.columns; concatenation alone only establishes sibling order.
*> table.concat a=`a` b=`b`*
Return *[Concat](table.concat(a=`a`, b=`b`))*.
## markdown
| 参数 | 类型 | 说明 |
|------|------|------|
| text | text | Plain Markdown content |
| slot | text | Stable component name |
| style | text | Optional class name |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| text | text | required | Plain Markdown content |
| slot | text | "" | Stable component name |
| style | text | "" | Optional class name |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | One Markdown leaf |
Use `text`, `slot`="", `style`="" as the inputs for this operation.
Make a leaf from Markdown `text`. Default `slot`="" and `style`="" keep
content independent of placement and theme. The returned list contains one
markdown row; the runtime renders headings, links, lists and tables. No native
@@ -87,21 +93,23 @@ plugin is loaded here, and no HTML is inserted into the authored component.
|---|------|------|-------|-------|-------|
| 1 | markdown | `slot` | `text` | "" | `style` |
*nodes*
Return *nodes*.
## wrap
| 参数 | 类型 | 说明 |
|------|------|------|
| children | list | Child node records |
| kind | text | Container kind |
| slot | text | Stable region name |
| style | text | Optional class name |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| children | list | required | Child node records |
| kind | text | "column" | Container kind |
| slot | text | "" | Stable region name |
| style | text | "" | Optional class name |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | One parent containing its child rows |
Use `children`, `kind`="column", `slot`="", `style`="" as the inputs for this operation.
Wrap `children` in one structural row. Default `kind`="column", `slot`=""
and `style`="" . Use row or column for geometry, nav/header/footer/section/aside
for a semantic region. The value cell holds the child list itself, not rendered
@@ -114,4 +122,4 @@ this pure constructor does not claim to validate a full site.
|---|------|------|-------|-------|-------|
| 1 | `kind` | `slot` | `children` | "" | `style` |
*nodes*
Return *nodes*.
+35 -29
View File
@@ -24,42 +24,52 @@ raw path; do not use raw to compensate for missing decomposition.
## from_markdown
| 参数 | 类型 | 说明 |
|------|------|------|
| text | text | Markdown source |
Turn Markdown `text` into a simple DOM map `{kind:"markdown", text}` for
`page.render` / `web.render`. This is the default body path for Document prose.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| text | text | required | Markdown source |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | DOM map |
**`out` = > table.put in=None at="kind" value="markdown"**
*> table.put in=`out` at="text" value=text*
Use `text` as the inputs for this operation.
Turn Markdown `text` into a simple DOM map `{kind:"markdown", text}` for
`page.render` / `web.render`. This is the default body path for Document prose.
We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="markdown"))**.
Return *[Set the text field in the new record](table.put(in=`out`, at="text", value=`text`))*.
## raw
| 参数 | 类型 | 说明 |
|------|------|------|
| html | text | raw HTML (escape hatch) |
Escape hatch — wrap raw `html`. Prefer Markdown / View nodes. Allowed only when
table-driven layout cannot express a host constraint; document the why next to
the call. Forbidden as the primary implementation of nav/sidebar/footer/home.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| html | text | required | raw HTML (escape hatch) |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | DOM map kind=raw |
**`out` = > table.put in=None at="kind" value="raw"**
*> table.put in=`out` at="html" value=html*
Use `html` as the inputs for this operation.
Escape hatch — wrap raw `html`. Prefer Markdown / View nodes. Allowed only when
table-driven layout cannot express a host constraint; document the why next to
the call. Forbidden as the primary implementation of nav/sidebar/footer/home.
We retain **`out` = [Set the kind field in the new record](table.put(in=None, at="kind", value="raw"))**.
Return *[Set the html field in the new record](table.put(in=`out`, at="html", value=`html`))*.
## render
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| dom | any | required | DOM map from from_markdown or raw |
| 返回 | 类型 | 说明 |
|------|------|------|
| dom | any | DOM map from from_markdown or raw |
| result | any | HTML text |
Use `dom` as the inputs for this operation.
Render DOM Artifact `dom` (from from_markdown or raw) to HTML via the native
plugin. When kind is markdown,
@@ -69,15 +79,11 @@ escape hatch documented on raw, not for assembling a full site shell. Prefer
feeding markdown DOM produced by from_markdown, or skip this helper and use
page.render / web.render on View tables from file-partitioned components.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML text |
> cap.load
**kind = [kind](access(dom, "kind"))**
We **[Load the native plugin required by this operation](cap.load())**.
We retain **`kind` = [Read kind field](access(`dom`, "kind"))**.
1. `kind` == "raw"
**html = [html](access(dom, "html"))**
*html*
We retain **`html` = [Read html field](access(`dom`, "html"))**.
Return *html*.
2. *
**text = [text](access(dom, "text"))**
*> web_dom_markdown text=`text`*
We retain **`text` = [Read text field](access(`dom`, "text"))**.
Return *[Render DOM Artifact dom (from from_markdown or raw) to HTML via the native plugin](web_dom_markdown(text=`text`))*.
+18 -12
View File
@@ -182,6 +182,8 @@ Return the workflow and stopping rule without creating files or claiming to
accept a particular site. Define the region tree, author parents and Markdown
leaves, then start and test the declared HTTP surface.
The returned rows are a planning aid, not a generated site or a validation certificate. Start with the component tree, give each parent one placement decision, then write the leaves as ordinary Markdown. Declare request-time handlers separately from startup assembly. Preview the composed result before starting the server, and compare real routes and narrow-screen geometry against that same source tree.
`workflow` =
| key | value |
@@ -196,7 +198,7 @@ leaves, then start and test the declared HTTP surface.
| step_G | compare preview and live output; test routes and browser geometry |
| stopping_rule | one Markdown responsibility and no internal layout |
*workflow*
Return *workflow*.
## layout_rules
@@ -208,40 +210,44 @@ Reuse the layout module convention without a second rule catalog. No
parameters or plugin. Actual acceptance still inspects leaf responsibilities,
parent relationships and the running result.
*> layout.rules*
Return *[Rules](layout.rules())*.
## preview_markdown
| 参数 | 类型 | 说明 |
|------|------|------|
| body | text | Markdown content |
| title | text | Document title |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| body | text | "" | Markdown content |
| title | text | "Preview" | Document title |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | HTML document |
Use `body`="", `title`="Preview" as the inputs for this operation.
Render Markdown `body`="" with default `title`="Preview" .
Return HTML text without writing files or registering routes. For a complex
page split the layout first; raw HTML strings are not the content strategy.
This tool needs the native plugin.
*> web.render body=`body` title=`title`*
Return *[Render](web.render(body=`body`, title=`title`))*.
## preview_nodes
| 参数 | 类型 | 说明 |
|------|------|------|
| nodes | list | Nested View rows |
| title | text | Document title |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| nodes | list | required | Nested View rows |
| title | text | "Preview" | Document title |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | HTML document |
Use `nodes`, `title`="Preview" as the inputs for this operation.
Render decomposed `nodes` with default `title`="Preview" .
Parent values retain child rows, while leaf values hold Markdown. Returning
HTML starts no server. The same renderer serves composed Documents, so this
preview checks that column relationships survive assembly.
*> web.render nodes=`nodes` title=`title`*
Return *[Render](web.render(nodes=`nodes`, title=`title`))*.
+38 -26
View File
@@ -37,12 +37,14 @@ plugins/web/internal/artifact with bilingual helpers and web_handbook tests.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Result |
| result | any | Column table with aligned key/value lists describing layout rules; no source inspection |
Return the engineering convention and stopping rule. No parameters or plugin.
This is guidance rather than evidence that a particular source file passes;
acceptance also requires reading the leaves and exercising the resulting page.
Apply the stopping rule to responsibilities rather than file size. A footer with two independent groups still needs child regions even if its text is short. A leaf containing several ordinary paragraphs may remain one Markdown responsibility when it needs no internal geometry. The parent imports those children and places them; the renderer supplies the resulting container structure. This table records that convention but does not inspect your files or certify that a layout works.
`out` =
| key | value |
@@ -56,7 +58,7 @@ acceptance also requires reading the leaves and exercising the resulting page.
| geometry | merge gives siblings; stack and columns give placement |
| verify | offline render; live routes; narrow and wide browser geometry |
*out*
Return *out*.
## view_schema
@@ -78,73 +80,83 @@ layout within one representation instead of adding a private fragment dialect.
| attrs |
| style |
*cols*
Return *cols*.
## merge_nodes
| 参数 | 类型 | 说明 |
|------|------|------|
| a | list | First node records |
| b | list | Second node records |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| a | list | required | First node records |
| b | list | required | Second node records |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | Ordered sibling nodes |
Use `a`, `b` as the inputs for this operation.
Concatenate `a` and `b` as siblings. This helper preserves structure and order
but does not imply geometry; use columns for side-by-side placement or stack
for a vertical page. The @ record lists retain nested values throughout.
*> component.merge a=`a` b=`b`*
Return *[Merge](component.merge(a=`a`, b=`b`))*.
## stack
| 参数 | 类型 | 说明 |
|------|------|------|
| children | list | Child component records |
| slot | text | Parent region name |
| style | text | Optional class name |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| children | list | required | Child component records |
| slot | text | "" | Parent region name |
| style | text | "" | Optional class name |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | Parent container rows |
Use `children`, `slot`="", `style`="" as the inputs for this operation.
Declare one vertical relationship for `children`. Default `slot`="" and
`style`="" . The parent owns placement while each imported child owns content
or its next decomposition level. Return View rows so another parent can wrap
them without first serializing any HTML.
*> component.wrap children=`children` kind="column" slot=`slot` style=`style`*
Return *[Wrap](component.wrap(children=`children`, kind="column", slot=`slot`, style=`style`))*.
## columns
| 参数 | 类型 | 说明 |
|------|------|------|
| children | list | Child component records |
| slot | text | Parent region name |
| style | text | Optional class name |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| children | list | required | Child component records |
| slot | text | "" | Parent region name |
| style | text | "" | Optional class name |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | Parent container rows |
Use `children`, `slot`="", `style`="" as the inputs for this operation.
Declare one responsive multi-column relationship for `children`. Default `slot`="" and
`style`="" . The parent owns placement while each imported child owns content
or its next decomposition level. Return View rows so another parent can wrap
them without first serializing any HTML.
*> component.wrap children=`children` kind="row" slot=`slot` style=`style`*
Return *[Wrap](component.wrap(children=`children`, kind="row", slot=`slot`, style=`style`))*.
## accept_component
| 参数 | 类型 | 说明 |
|------|------|------|
| name | text | Component name |
| duty | text | One responsibility |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| name | text | required | Component name |
| duty | text | required | One responsibility |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Result |
| result | any | Checklist record with status, name, duty and check; it does not certify a component |
Use `name`, `duty` as the inputs for this operation.
Return a review checklist for component `name` and stated `duty`. Two strings
cannot establish source quality or a working layout, so this tool does not
@@ -157,4 +169,4 @@ before accepting the component. It never writes or scans files.
|--------|------|------|-------|
| checklist | `name` | `duty` | one Markdown leaf or one parent relationship; no raw HTML shell |
*row*
Return *row*.
+84 -75
View File
@@ -26,45 +26,57 @@ preserve tests/ext/web-artifact-render-smoke.mq.md and the handbook tests.
## new
| 参数 | 类型 | 说明 |
|------|------|------|
| title | text | document title |
| route | text | path |
| method | text | HTTP method |
| body | text | Markdown body |
| nodes | any | View table or None |
| data_source | text | table name |
| data_order | text | order key |
| data_where | text | filters |
Construct a Document handle with `title`="", `route`="/", `method`="GET",
`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="",
`data_where`="" keys. Prefer Artifact discovery via serve for production pages;
use this tool for previews and stepwise agent sessions. nodes must be the
unified View schema, never a private dialect or an HTML string shell.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| title | text | "" | document title |
| route | text | "/" | path |
| method | text | "GET" | HTTP method |
| body | text | "" | Markdown body |
| nodes | any | None | View table or None |
| data_source | text | "" | table name |
| data_order | text | "" | order key |
| data_where | text | "" | filters |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | page handle |
> cap.load
Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation.
Construct a Document handle with `title`="", `route`="/", `method`="GET",
`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="",
`data_where`="" keys. Prefer Artifact discovery via serve for production pages;
use this tool for previews and stepwise agent sessions. nodes must be the
unified View schema, never a private dialect or an HTML string shell.
We **[Load the native plugin required by this operation](cap.load())**.
`out` =
| _type | title | route | method | body | nodes | data_source | data_order | data_where |
|-------|-------|-------|--------|------|-------|-------------|------------|------------|
| page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` |
*out*
Return *out*.
## render
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| page | any | required | Document handle |
| nodes | any | None | View table or None |
| db | any | None | optional database handle |
| 返回 | 类型 | 说明 |
|------|------|------|
| page | any | Document handle |
| nodes | any | View table or None |
| db | any | optional database handle |
| result | any | HTML or render payload |
Use `page`, `nodes`=None, `db`=None as the inputs for this operation.
Render Document handle `page` to HTML for preview or response. Optional
`nodes`=None is the unified View table; when None, uses the page's own nodes or
Markdown body. Optional `db`=None is retained for facade compatibility. This offline renderer
does not populate data_source; automatic row binding belongs to served ordinary
@@ -74,64 +86,65 @@ handmade HTML string as the page shell. This is the sole compose path (ADR
0007); there is no compose_main or fragment DSL. Agents should call this free
tool (not a method chain) under `--effects plugin`.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML or render payload |
> cap.load
**n = nodes**
We **[Load the native plugin required by this operation](cap.load())**.
We retain **n = nodes**.
1. `n` == None
**n = [nodes](access(page, "nodes"))**
We retain **`n` = [Read nodes field](access(`page`, "nodes"))**.
2. *
**_ = 1**
**title = [title](access(page, "title"))**
We retain **`title` = [Read title field](access(`page`, "title"))**.
1. `n`
*> web_render_nodes page=`page` nodes=`n` db=`db` title=`title`*
Return *[Render Document handle page to HTML for preview or response](web_render_nodes(page=`page`, nodes=`n`, db=`db`, title=`title`))*.
2. *
**body = [body](access(page, "body"))**
*> web_render_document page=`page` body=`body` db=`db` title=`title`*
We retain **`body` = [Read body field](access(`page`, "body"))**.
Return *[Render Document handle page to HTML for preview or response](web_render_document(page=`page`, body=`body`, db=`db`, title=`title`))*.
# page
| 参数 | 类型 | 说明 |
|------|------|------|
| title | any | See prose default / 见叙述默认值 |
| route | any | See prose default / 见叙述默认值 |
| method | any | See prose default / 见叙述默认值 |
| body | any | See prose default / 见叙述默认值 |
| nodes | any | See prose default / 见叙述默认值 |
| data_source | any | See prose default / 见叙述默认值 |
| data_order | any | See prose default / 见叙述默认值 |
| data_where | any | See prose default / 见叙述默认值 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| title | any | "" | Document title used by preview and page rendering |
| route | any | "/" | Declared URL path at which this Document may be mounted |
| method | any | "GET" | HTTP request method for the declared route |
| body | any | "" | Markdown document content; complex sites use recursively split components |
| nodes | any | None | Nested View records, or None to retain document-body rendering |
| data_source | any | "" | Document data source declaration; empty means no automatic source |
| data_order | any | "" | Ordering declaration for the selected document data source |
| data_where | any | "" | Filter declaration for the selected document data source |
Inputs: `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`=""
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Document handle retaining title, route, method, body, nodes and data declarations |
Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation.
Web Document handle for author method chains. Prefer constructing from Artifact
Metadata via `web.page` facade or the free `new` tool above. View tables use
only `|type|slot|value|attrs|style|` (ZH `|类型|槽|值|属性|样式|`). Do not pass a
raw HTML string as the primary `body` for a full site shell.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Constructed value / 构造结果 |
We **[Load the native plugin required by this operation](cap.load())**.
> cap.load
`out` =
| _type | title | route | method | body | nodes | data_source | data_order | data_where |
|-------|-------|-------|--------|------|-------|-------------|------------|------------|
| page | `title` | `route` | `method` | `body` | `nodes` | `data_source` | `data_order` | `data_where` |
*out*
Return *out*.
## render
| 参数 | 类型 | 说明 |
|------|------|------|
| nodes | any | View table or None |
| db | any | optional database handle |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| nodes | any | None | View table or None |
| db | any | None | optional database handle |
Inputs: `nodes`=None, `db`=None
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML or render payload |
Use `nodes`=None, `db`=None as the inputs for this operation.
Render this Document to HTML for preview or response. Optional `nodes` is the
unified View table (type/slot/value/attrs/style). When `nodes` is None, the
@@ -141,39 +154,35 @@ file-partitioned components via component.merge — do not pass a handmade HTML
string as the page shell. This is the sole compose path (ADR 0007); there is no
compose_main or fragment DSL.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML or render payload |
> cap.load
**n = nodes**
We **[Load the native plugin required by this operation](cap.load())**.
We retain **n = nodes**.
1. `n` == None
**n = [nodes](access(self, "nodes"))**
We retain **`n` = [Read nodes field](access(`self`, "nodes"))**.
2. *
**_ = 1**
**title = [title](access(self, "title"))**
We retain **`title` = [Read title field](access(`self`, "title"))**.
1. `n`
*> web_render_nodes page=`self` nodes=`n` db=`db` title=`title`*
Return *[Render this Document to HTML for preview or response](web_render_nodes(page=`self`, nodes=`n`, db=`db`, title=`title`))*.
2. *
**body = [body](access(self, "body"))**
*> web_render_document page=`self` body=`body` db=`db` title=`title`*
We retain **`body` = [Read body field](access(`self`, "body"))**.
Return *[Render this Document to HTML for preview or response](web_render_document(page=`self`, body=`body`, db=`db`, title=`title`))*.
## css
| 参数 | 类型 | 说明 |
|------|------|------|
| css | text | raw CSS (escape hatch) |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| css | text | required | raw CSS (escape hatch) |
Inputs: `css`
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | updated page handle |
Use `css` as the inputs for this operation.
Escape hatch — append raw CSS string `css` to this page. Named style tables and
the View style column remain the default theme path. Use this only when a host
constraint cannot be expressed as a named style row, and write that reason next
to the call. Forbidden as the primary way to style nav, sidebar, or footer.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | updated page handle |
> cap.load
*> web_page_css page=`self` css=`css`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Escape hatch — append raw CSS string css to this page](web_page_css(page=`self`, css=`css`))*.
+111 -101
View File
@@ -25,44 +25,55 @@ changes; never introduce undeclared user URLs as a hidden convenience.
## new
| 参数 | 类型 | 说明 |
|------|------|------|
| app | any | app handle |
| path | text | URL path |
| method | text | HTTP method |
| page | any | Document or None |
| fn | text | endpoint member |
| request | text | request kind |
| response | text | response kind |
| auth | text | auth tag |
| class | text | route class |
Build a declared route handle for `app` at `path` with `method`="GET" .
`page`=None holds a Document; `fn`="" names an Endpoint lib.member.
`request`="json", `response`="json", `auth`="", and `class`="" document the
contract. Optional class values: execute, short, read, control (empty →
heuristic / legacy_serial). This tool does not register yet — call `register`
or use the facade `web.route` which registers in one step.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | required | app handle |
| path | text | required | URL path |
| method | text | "GET" | HTTP method |
| page | any | None | Document or None |
| fn | text | "" | endpoint member |
| request | text | "json" | request kind |
| response | text | "json" | response kind |
| auth | text | "" | auth tag |
| class | text | "" | route class |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | route handle |
> cap.load
Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation.
Build a declared route handle for `app` at `path` with `method`="GET" .
`page`=None holds a Document; `fn`="" names an Endpoint lib.member.
`request`="json", `response`="json", `auth`="", and `class`="" document the
contract. Optional class values: execute, short, read, control (empty →
heuristic / legacy_serial). This tool does not register yet — call `register`
or use the facade `web.route` which registers in one step.
We **[Load the native plugin required by this operation](cap.load())**.
`out` =
| _type | app | path | method | page | fn | request | response | auth | class |
|-------|-----|------|--------|------|----|---------|----------|------|-------|
| route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` |
*out*
Return *out*.
## register
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| route | any | required | route handle |
| app | any | None | app or None |
| 返回 | 类型 | 说明 |
|------|------|------|
| route | any | route handle |
| app | any | app or None |
| result | any | registration result |
Use `route`, `app`=None as the inputs for this operation.
Register declared route handle `route` on an app. Optional `app`=None falls back
to the app stored on the route object so stepwise agent sessions can omit it.
@@ -73,108 +84,111 @@ free tool under `--effects plugin` rather than a method chain when driving
registration from `marqdo call`. Soft-fails with ok=False when neither page nor
fn is present, so callers can detect incomplete declarations early.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | registration result |
> cap.load
**a = app**
We **[Load the native plugin required by this operation](cap.load())**.
We retain **a = app**.
1. `a` == None
**a = [app](access(route, "app"))**
We retain **`a` = [Read app field](access(`route`, "app"))**.
2. *
**_ = 1**
**page = [page](access(route, "page"))**
**fn = [fn](access(route, "fn"))**
We retain **`page` = [Read page field](access(`route`, "page"))**.
We retain **`fn` = [Read fn field](access(`route`, "fn"))**.
1. `page`
**path = [path](access(route, "path"))**
*> web_app_route app=`a` path=`path` page=`page`*
We retain **`path` = [Read path field](access(`route`, "path"))**.
Return *[Register declared route handle route on an app](web_app_route(app=`a`, path=`path`, page=`page`))*.
2. `fn`
**path = [path](access(route, "path"))**
**method = [method](access(route, "method"))**
**request = [request](access(route, "request"))**
**response = [response](access(route, "response"))**
**class = [class](access(route, "class"))**
*> web_app_invoke app=`a` path=`path` method=`method` fn=`fn` body=`request` return=`response` class=`class`*
We retain **`path` = [Read path field](access(`route`, "path"))**.
We retain **`method` = [Read method field](access(`route`, "method"))**.
We retain **`request` = [Read request field](access(`route`, "request"))**.
We retain **`response` = [Read response field](access(`route`, "response"))**.
We retain **`class` = [Read class field](access(`route`, "class"))**.
Return *[Register declared route handle route on an app](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*.
3. *
*> table.put in=None at="ok" value=False*
Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*.
## use
| 参数 | 类型 | 说明 |
|------|------|------|
| route | any | route handle |
| middleware | any | middleware table |
Attach middleware table `middleware` to declared route handle `route`
(`|header|value|` or named capability rows). Prefer first-class middleware tables
over configure junk drawers. Call this free tool with `--effects plugin`.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| middleware | any | required | middleware table |
| route | any | required | route handle |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | use result |
> cap.load
*> web_route_use route=`route` middleware=`middleware`*
Use `middleware`, `route` as the inputs for this operation.
Attach middleware table `middleware` to declared route handle `route`
(`|header|value|` or named capability rows). Prefer first-class middleware tables
over configure junk drawers. Call this free tool with `--effects plugin`.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Attach middleware table middleware to declared route handle route (|header|value| or named capability rows)](web_route_use(route=`route`, middleware=`middleware`))*.
# route
| 参数 | 类型 | 说明 |
|------|------|------|
| app | any | See prose default / 见叙述默认值 |
| path | any | See prose default / 见叙述默认值 |
| method | any | See prose default / 见叙述默认值 |
| page | any | See prose default / 见叙述默认值 |
| fn | any | See prose default / 见叙述默认值 |
| request | any | See prose default / 见叙述默认值 |
| response | any | See prose default / 见叙述默认值 |
| auth | any | See prose default / 见叙述默认值 |
| class | any | See prose default / 见叙述默认值 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | required | Application handle created by the public web app constructor |
| path | any | required | URL path declared for this route |
| method | any | "GET" | HTTP request method for the declared route |
| page | any | None | Initial Document/page resource, or None for explicit later route mounts |
| fn | any | "" | Endpoint member path; empty when mounting a Document page |
| request | any | "json" | Request body format passed to the native Endpoint dispatcher |
| response | any | "json" | Response format passed to the native Endpoint dispatcher |
| auth | any | "" | Explicit route authentication policy label |
| class | any | "" | Execution class: execute, short, read or control; empty keeps native heuristics |
Inputs: `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`=""
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Declared route handle retaining app, path, method, page or endpoint and dispatch fields |
Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation.
Declared route handle for author method chains. Prefer `web.route` / Artifact
`type: endpoint` discovery via `web.serve`. Optional `class`: `execute` |
`short` | `read` | `control` (empty → heuristic / `legacy_serial`).
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Constructed value / 构造结果 |
We **[Load the native plugin required by this operation](cap.load())**.
> cap.load
`out` =
| _type | app | path | method | page | fn | request | response | auth | class |
|-------|-----|------|--------|------|----|---------|----------|------|-------|
| route | `app` | `path` | `method` | `page` | `fn` | `request` | `response` | `auth` | `class` |
*out*
Return *out*.
## use
| 参数 | 类型 | 说明 |
|------|------|------|
| middleware | any | middleware table |
Inputs: `middleware`
Attach middleware table to this route (`|header|value|` or named capability
rows). Prefer explicit tables authors can read; do not restore a configure bag
for headers and cors.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| middleware | any | required | middleware table |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | use result |
> cap.load
*> web_route_use route=`self` middleware=`middleware`*
Use `middleware` as the inputs for this operation.
Attach middleware table to this route (`|header|value|` or named capability
rows). Prefer explicit tables authors can read; do not restore a configure bag
for headers and cors.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Attach middleware table to this route (|header|value| or named capability rows)](web_route_use(route=`self`, middleware=`middleware`))*.
## register
| 参数 | 类型 | 说明 |
|------|------|------|
| app | any | app or None |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | None | app or None |
Inputs: `app`=None
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | registration result |
Use `app`=None as the inputs for this operation.
Register this declared route on an app handle. When optional `app` is None, use
the app stored on this route object so author chains can omit the argument after
@@ -187,27 +201,23 @@ page nor fn is set, so callers can detect an incomplete declaration without a
hard crash. Never invents an undeclared path — registration only publishes what
this handle already carries.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | registration result |
> cap.load
**a = app**
We **[Load the native plugin required by this operation](cap.load())**.
We retain **a = app**.
1. `a` == None
**a = [app](access(self, "app"))**
We retain **`a` = [Read app field](access(`self`, "app"))**.
2. *
**_ = 1**
**page = [page](access(self, "page"))**
**fn = [fn](access(self, "fn"))**
We retain **`page` = [Read page field](access(`self`, "page"))**.
We retain **`fn` = [Read fn field](access(`self`, "fn"))**.
1. `page`
**path = [path](access(self, "path"))**
*> web_app_route app=`a` path=`path` page=`page`*
We retain **`path` = [Read path field](access(`self`, "path"))**.
Return *[Register this declared route on an app handle](web_app_route(app=`a`, path=`path`, page=`page`))*.
2. `fn`
**path = [path](access(self, "path"))**
**method = [method](access(self, "method"))**
**request = [request](access(self, "request"))**
**response = [response](access(self, "response"))**
**class = [class](access(self, "class"))**
*> web_app_invoke app=`a` path=`path` method=`method` fn=`fn` body=`request` return=`response` class=`class`*
We retain **`path` = [Read path field](access(`self`, "path"))**.
We retain **`method` = [Read method field](access(`self`, "method"))**.
We retain **`request` = [Read request field](access(`self`, "request"))**.
We retain **`response` = [Read response field](access(`self`, "response"))**.
We retain **`class` = [Read class field](access(`self`, "class"))**.
Return *[Register this declared route on an app handle](web_app_invoke(app=`a`, path=`path`, method=`method`, fn=`fn`, body=`request`, return=`response`, class=`class`))*.
3. *
*> table.put in=None at="ok" value=False*
Return *[Set the ok field in the new record](table.put(in=None, at="ok", value=False))*.
+220 -184
View File
@@ -35,110 +35,128 @@ route API. Contracts precede execution; ordinary prose titles are not functions.
## page
| 参数 | 类型 | 说明 |
|------|------|------|
| title | text | document title |
| route | text | path |
| method | text | HTTP method |
| body | text | Markdown body |
| nodes | any | View table or None |
| data_source | text | table name |
| data_order | text | order key |
| data_where | text | filters |
Construct a Document handle with `title`="", `route`="/", `method`="GET",
`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="",
`data_where`="" keys. Prefer discovering type: web Artifact files via serve
rather than hand-building every page in memory. nodes must be the unified View
schema, never a private dialect or an HTML string shell.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| title | text | "" | document title |
| route | text | "/" | path |
| method | text | "GET" | HTTP method |
| body | text | "" | Markdown body |
| nodes | any | None | View table or None |
| data_source | text | "" | table name |
| data_order | text | "" | order key |
| data_where | text | "" | filters |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | page handle |
*> page_mod.page title=`title` route=`route` method=`method` body=`body` nodes=`nodes` data_source=`data_source` data_order=`data_order` data_where=`data_where`*
Use `title`="", `route`="/", `method`="GET", `body`="", `nodes`=None, `data_source`="", `data_order`="", `data_where`="" as the inputs for this operation.
Construct a Document handle with `title`="", `route`="/", `method`="GET",
`body`="", optional View `nodes`=None, and flat `data_source`="", `data_order`="",
`data_where`="" keys. Prefer discovering type: web Artifact files via serve
rather than hand-building every page in memory. nodes must be the unified View
schema, never a private dialect or an HTML string shell.
Return *[Page](page_mod.page(title=`title`, route=`route`, method=`method`, body=`body`, nodes=`nodes`, data_source=`data_source`, data_order=`data_order`, data_where=`data_where`))*.
## route
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | required | app handle |
| path | text | required | URL path |
| method | text | "GET" | HTTP method |
| page | any | None | Document or None |
| fn | text | "" | endpoint member |
| request | text | "json" | request kind |
| response | text | "json" | response kind |
| auth | text | "" | auth tag |
| class | text | "" | route class |
| 返回 | 类型 | 说明 |
|------|------|------|
| app | any | app handle |
| path | text | URL path |
| method | text | HTTP method |
| page | any | Document or None |
| fn | text | endpoint member |
| request | text | request kind |
| response | text | response kind |
| auth | text | auth tag |
| class | text | route class |
| result | any | registration result |
Use `app`, `path`, `method`="GET", `page`=None, `fn`="", `request`="json", `response`="json", `auth`="", `class`="" as the inputs for this operation.
Register a declared Document page or Endpoint on `app` at `path` with
`method`="GET" . `page`=None holds a Document; `fn`="" names an Endpoint
lib.member. `request`="json", `response`="json", `auth`="", and `class`=""
document the contract. Optional class values include execute, short, read,
control. User routes must be declared — never implicit. After building the
route object this tool registers it on the app.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | registration result |
**r = > route_mod.route app=`app` path=`path` method=`method` page=`page` fn=`fn` request=`request` response=`response` auth=`auth` class=`class`**
*> `r`.register app=`app`*
We retain **`r` = [Route](route_mod.route(app=`app`, path=`path`, method=`method`, page=`page`, fn=`fn`, request=`request`, response=`response`, auth=`auth`, class=`class`))**.
Return *[Register](> `r`.register app=`app` )*.
## render
| 参数 | 类型 | 说明 |
|------|------|------|
| doc | any | Document or None |
| nodes | any | View table or None |
| body | text | Markdown |
| title | text | title |
| db | any | optional db |
Render a Document or View nodes to HTML for offline preview. Prefer nodes from
file-partitioned components. Optional `doc`=None is a Document handle; when set,
delegates to page.render. Optional `nodes`=None is a View table; when set without
doc, renders that table. Otherwise renders Markdown `body`="" with optional
`title`="" and `db`=None . Requires the native plugin. Do not treat this as
permission to paste a full HTML homepage — keep using View tables and Markdown.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| doc | any | None | Document or None |
| nodes | any | None | View table or None |
| body | text | "" | Markdown |
| title | text | "" | title supplied by the caller |
| db | any | None | optional db |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML or payload |
> cap.load
Use `doc`=None, `nodes`=None, `body`="", `title`="", `db`=None as the inputs for this operation.
Render a Document or View nodes to HTML for offline preview. Prefer nodes from
file-partitioned components. Optional `doc`=None is a Document handle; when set,
delegates to page.render. Optional `nodes`=None is a View table; when set without
doc, renders that table. Otherwise renders Markdown `body`="" with optional
`title`="" and `db`=None . Requires the native plugin. Do not treat this as
permission to paste a full HTML homepage — keep using View tables and Markdown.
We **[Load the native plugin required by this operation](cap.load())**.
1. `doc`
*> `doc`.render nodes=`nodes` db=`db`*
Return *[Render](> `doc`.render nodes=`nodes` db=`db` )*.
2. `nodes`
*> web_render_nodes page=`doc` nodes=`nodes` db=`db` title=`title`*
Return *[Render a Document or View nodes to HTML for offline preview](web_render_nodes(page=`doc`, nodes=`nodes`, db=`db`, title=`title`))*.
3. *
*> web_render_document page=`doc` body=`body` db=`db` title=`title`*
Return *[Render a Document or View nodes to HTML for offline preview](web_render_document(page=`doc`, body=`body`, db=`db`, title=`title`))*.
## use
| 参数 | 类型 | 说明 |
|------|------|------|
| app | any | app handle |
| middleware | any | middleware table |
Attach first-class `middleware` to `app`. Pass a GFM table (security headers,
cors row, and similar). This replaces the old configure(...) junk drawer with an
explicit table authors can read.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| middleware | any | required | middleware table |
| app | any | required | app handle |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | app handle |
> cap.load
*> web_app_use app=`app` middleware=`middleware`*
Use `middleware`, `app` as the inputs for this operation.
Attach first-class `middleware` to `app`. Pass a GFM table (security headers,
cors row, and similar). This replaces the old configure(...) junk drawer with an
explicit table authors can read.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Attach first-class middleware to app](web_app_use(app=`app`, middleware=`middleware`))*.
## inspect
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| app | any | None | app or None |
| root | text | "" | Site directory to inspect without listening |
| 返回 | 类型 | 说明 |
|------|------|------|
| app | any | app or None |
| root | text | Site directory to inspect without listening |
| result | any | {declared, system} |
Use `app`=None, `root`="" as the inputs for this operation.
Return declared versus system route tables for introspection. System routes such
as /_part and /_form must appear here. Use this to verify a site after serve or
@@ -146,23 +164,25 @@ manual registration. Optional `app`=None selects which application to inspect.
Optional `root`="" scans a site directory when supplied; it does not start a server.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | {declared, system} |
> cap.load
*> web_inspect app=`app` root=`root`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Return declared versus system route tables for introspection](web_inspect(app=`app`, root=`root`))*.
## serve
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| root | text | "." | site root |
| host | text | "127.0.0.1" | bind host |
| port | number | 18081 | Explicit server port |
| db | any | None | optional db |
| static_dir | text | "" | static files |
| middleware | any | None | optional middleware |
| 返回 | 类型 | 说明 |
|------|------|------|
| root | text | site root |
| host | text | bind host |
| port | number | port |
| db | any | optional db |
| static_dir | text | static files |
| middleware | any | optional middleware |
| result | any | serve result |
Use `root`=".", `host`="127.0.0.1", `port`=18081, `db`=None, `static_dir`="", `middleware`=None as the inputs for this operation.
Scan `root`="." for type web or endpoint Artifacts, register declared routes,
attach system routes, and listen on `host`="127.0.0.1" and `port`=18081 . The
@@ -170,138 +190,153 @@ site directory should already follow the layout law (components split until
simple). Optional `db`=None, `static_dir`="", and `middleware`=None bind
resources without stuffing them into this facade as author APIs.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | serve result |
> cap.load
*> web_serve_root root=`root` host=`host` port=`port` db=`db` static_dir=`static_dir` middleware=`middleware`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Scan root="](web_serve_root(root=`root`, host=`host`, port=`port`, db=`db`, static_dir=`static_dir`, middleware=`middleware`))*.
## client_embed
| 参数 | 类型 | 说明 |
|------|------|------|
| bridge | text | bridge script URL |
| wasm | text | wasm URL |
| source | text | optional source |
| boot | bool | auto boot |
Describe WASM bridge embed tags for a page that needs client Marqdo. Defaults:
`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm",
`source`="", `boot`=True . This is not a substitute for Document layout: still
partition nav and main in files, then embed the bridge where interaction needs
it.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| bridge | text | "/static/marqdo-bridge.js" | bridge script URL |
| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL |
| source | text | "" | optional source |
| boot | bool | True | auto boot |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | embed descriptor |
*> client_mod.embed bridge=`bridge` wasm=`wasm` source=`source` boot=`boot`*
Use `bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm", `source`="", `boot`=True as the inputs for this operation.
Describe WASM bridge embed tags for a page that needs client Marqdo. Defaults:
`bridge`="/static/marqdo-bridge.js", `wasm`="/static/marqdo_wasm.wasm",
`source`="", `boot`=True . This is not a substitute for Document layout: still
partition nav and main in files, then embed the bridge where interaction needs
it.
Return *[Embed](client_mod.embed(bridge=`bridge`, wasm=`wasm`, source=`source`, boot=`boot`))*.
## text_patch
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sel | text | required | CSS selector |
| text | text | required | new text |
| 返回 | 类型 | 说明 |
|------|------|------|
| sel | text | CSS selector |
| text | text | new text |
| result | any | patch descriptor |
Use `sel`, `text` as the inputs for this operation.
Client patch: set text content for CSS selector `sel` to string `text`. Use for
small interactive updates after a Document is already laid out with View tables —
not for building the initial homepage shell.
Return *[Text patch](client_mod.text_patch(sel=`sel`, text=`text`))*.
## dom_patch
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| sel | text | required | CSS selector |
| html | text | "" | optional HTML fragment |
| attrs | any | None | optional attrs |
| remove | bool | False | remove node |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | patch descriptor |
*> client_mod.text_patch sel=`sel` text=`text`*
## dom_patch
| 参数 | 类型 | 说明 |
|------|------|------|
| sel | text | CSS selector |
| html | text | optional HTML fragment |
| attrs | any | optional attrs |
| remove | bool | remove node |
Use `sel`, `html`="", `attrs`=None, `remove`=False as the inputs for this operation.
Client patch for selector `sel` with optional `html`="", `attrs`=None, or
`remove`=False . Treat html here as a surgical update, never as the primary way
to author nav, sidebar, or footer. Layout law still applies to the Document that
hosts the selector.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | patch descriptor |
*> client_mod.dom_patch sel=`sel` html=`html` attrs=`attrs` remove=`remove`*
Return *[Dom patch](client_mod.dom_patch(sel=`sel`, html=`html`, attrs=`attrs`, remove=`remove`))*.
## make_style
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | property table |
| name | text | "" | style name |
| strict | bool | False | strict mode |
| 返回 | 类型 | 说明 |
|------|------|------|
| name | text | style name |
| table | any | property table |
| strict | bool | strict mode |
| result | any | CSS / style handle |
Use `table`, `name`="", `strict`=False as the inputs for this operation.
Compile a named style `table` into CSS. Optional `name`="" and `strict`=False .
Styles remain data next to content; this is not a hidden page DSL. Prefer
referencing style names from View style columns after file-partitioned
components define their look.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | CSS / style handle |
> cap.load
*> web_style name=`name` table=`table` strict=`strict`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Compile a named style table into CSS](web_style(name=`name`, table=`table`, strict=`strict`))*.
## make_images
| 参数 | 类型 | 说明 |
|------|------|------|
| table | any | images table |
Build image descriptors from a readable `table` of sources and alts. Keep media
declarations in Markdown tables beside the Document that uses them.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | images table |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | images payload |
> cap.load
*> web_images table=`table`*
Use `table` as the inputs for this operation.
Build image descriptors from a readable `table` of sources and alts. Keep media
declarations in Markdown tables beside the Document that uses them.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Build image descriptors from a readable table of sources and alts. Keep media declarations in Markdown tables beside the Document that uses them.](web_images(table=`table`))*.
## make_head
| 参数 | 类型 | 说明 |
|------|------|------|
| table | any | head table |
Build head resource rows (link, script, icon) from a `table`. Prefer declaring
head needs as data rather than injecting opaque HTML head strings.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| table | any | required | head table |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | head payload |
> cap.load
*> web_head table=`table`*
Use `table` as the inputs for this operation.
Build head resource rows (link, script, icon) from a `table`. Prefer declaring
head needs as data rather than injecting opaque HTML head strings.
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Build head resource rows (link, script, icon) from a table. Prefer declaring head needs as data rather than injecting opaque HTML head strings.](web_head(table=`table`))*.
# app
| 参数 | 类型 | 说明 |
|------|------|------|
| page | any | See prose default / 见叙述默认值 |
| db | any | See prose default / 见叙述默认值 |
| host | any | See prose default / 见叙述默认值 |
| port | any | See prose default / 见叙述默认值 |
| admin | any | See prose default / 见叙述默认值 |
| admin_prefix | any | See prose default / 见叙述默认值 |
| shell_css | any | See prose default / 见叙述默认值 |
| layout | any | See prose default / 见叙述默认值 |
| asset_version | any | See prose default / 见叙述默认值 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| page | any | None | Initial Document/page resource, or None for explicit later route mounts |
| db | any | None | Existing database resource used for document data and native application services |
| host | any | "127.0.0.1" | Listen address; the default binds only the local host |
| port | any | 18081 | TCP listen port selected for the application |
| admin | any | False | Whether to enable the native administration routes |
| admin_prefix | any | "/admin" | URL prefix under which native administration routes are mounted |
| shell_css | any | None | Optional native shell stylesheet configuration; None keeps the runtime default |
| layout | any | None | Optional native shell layout configuration; component geometry remains View data |
| asset_version | any | None | Optional resource version used by the native shell for asset URLs |
Inputs: `page`=None, `db`=None, `host`=127.0.0.1, `port`=18081, `admin`=False, `admin_prefix`="/admin", `shell_css`=None, `layout`=None, `asset_version`=None
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Native app resource for static mounts, route registration, gates and listening |
Use `page`=None, `db`=None, `host`="127.0.0.1", `port`=18081, `admin`=False, `admin_prefix`="/admin", `shell_css`=None, `layout`=None, `asset_version`=None as the inputs for this operation.
Low-level app handle for advanced mounts. Prefer web.serve for Artifact sites
that already follow file-partition layout. Optional page, db, host, port, admin
@@ -311,59 +346,60 @@ discovery should stay on serve; agents should not invent HTML shells on this
object. Methods static, listen, and gate hang off the returned handle for
mounts that remain table- and Metadata-driven.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Constructed value / 构造结果 |
> cap.load
*> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=None logout_redirect=None shell_css=`shell_css` layout=`layout` asset_version=`asset_version`*
We **[Load the native plugin required by this operation](cap.load())**.
Return *[Low-level app handle for advanced mounts](web_app_new(page=`page`, db=`db`, admin=`admin`, host=`host`, port=`port`, admin_prefix=`admin_prefix`, login_redirect=None, logout_redirect=None, shell_css=`shell_css`, layout=`layout`, asset_version=`asset_version`))*.
## static
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| dir | text | required | filesystem directory |
| mount | text | "/static" | URL mount |
| 返回 | 类型 | 说明 |
|------|------|------|
| dir | text | filesystem directory |
| mount | text | URL mount |
| result | any | app handle |
Use `dir`, `mount`="/static" as the inputs for this operation.
Mount static files from `dir` at `mount`=/static on this app. Use for bridge
scripts and assets referenced by Documents — not for dumping an HTML-only site
tree that bypasses Artifact Documents.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | app handle |
*> web_app_static app=`self` dir=`dir` mount=`mount`*
Return *[Mount static files from dir at mount=/static on this app](web_app_static(app=`self`, dir=`dir`, mount=`mount`))*.
## listen
Start listening with the already configured app host and port. Prefer serve for
root scanning; listen is for advanced app handles after manual route setup.
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | listen result |
*> web_listen app=`self`*
Start listening with the already configured app host and port. Prefer serve for
root scanning; listen is for advanced app handles after manual route setup.
Return *[Start listening with the already configured app host and port. Prefer serve for root scanning; listen is for advanced app handles after manual route setup.](web_listen(app=`self`))*.
## gate
| 参数 | 类型 | 说明 |
|------|------|------|
| path | text | gated path |
| roles | any | roles |
| permissions | text | permissions |
| match | text | match mode |
| on_deny | text | deny behavior |
| exclude | any | exclusions |
Attach an authorization gate on `path` for this app. Defaults: `roles`="admin",
`permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None . Auth
resources live in ext/security; this method only wires the gate onto the web
app surface.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| path | text | required | gated path |
| roles | any | "admin" | roles supplied by the caller |
| permissions | text | "" | Comma-separated permission names held by the current role or subject |
| match | text | "prefix" | match mode |
| on_deny | text | "forbid" | deny behavior |
| exclude | any | None | exclusions |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | app handle |
*> web_app_gate app=`self` path=`path` roles=`roles` permissions=`permissions` match=`match` on_deny=`on_deny` exclude=`exclude`*
Use `path`, `roles`="admin", `permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None as the inputs for this operation.
Attach an authorization gate on `path` for this app. Defaults: `roles`="admin",
`permissions`="", `match`="prefix", `on_deny`="forbid", `exclude`=None . Auth
resources live in ext/security; this method only wires the gate onto the web
app surface.
Return *[Attach an authorization gate on path for this app](web_app_gate(app=`self`, path=`path`, roles=`roles`, permissions=`permissions`, match=`match`, on_deny=`on_deny`, exclude=`exclude`))*.
+32 -24
View File
@@ -36,7 +36,7 @@ marqdo call ext/web/布局/索引.mq.md 分栏 '子节点=[{"type":"markdown","v
返回先拆布局、递归到 Markdown 叶子的工程约定。无参数;
规则是说明,不声称已静态审查某个文件。真正验收需要运行并检查站点。
*> layout.rules*
完成后返回*[调用 rules](layout.rules())*。
## 视图契约
@@ -47,72 +47,80 @@ marqdo call ext/web/布局/索引.mq.md 分栏 '子节点=[{"type":"markdown","v
返回五个公共列名。子块通过值列继续包含同样的 View 记录;
不增加第二种布局表方言,也不把任意属性名解释为 CSS。
*> layout.view_schema*
完成后返回*[调用 view schema](layout.view_schema())*。
## 合并节点
| 参数 | 类型 | 说明 |
|------|------|------|
| 甲 | list | 第一组节点 |
| 乙 | list | 第二组节点 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 甲 | list | 必填 | 第一组节点 |
| 乙 | list | 必填 | 第二组节点 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 兄弟节点 |
这里使用`甲`、`乙`。
拼接 `甲` 与 `乙`,只保留顺序,不增加几何关系。
需要横向排列时使用分栏,需要上下分区时使用纵排。
*> layout.merge_nodes a=`甲` b=`乙`*
完成后返回*[调用 merge nodes](layout.merge_nodes(a=`甲`, b=`乙`))*。
## 纵排
| 参数 | 类型 | 说明 |
|------|------|------|
| 子节点 | list | 子块列表 |
| 槽 | text | 父区域名 |
| 样式 | text | 可选类名 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 子节点 | list | 必填 | 子块列表 |
| 槽 | text | "" | 父区域名 |
| 样式 | text | "" | 可选类名 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 父容器节点 |
这里使用`子节点`、`槽`=""、`样式`=""。
为 `子节点` 声明一层上下顺序。默认 `槽`=""、`样式`=""。
父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表,
可以继续传给祖先组件或页面渲染,无需提前转为 HTML。
*> layout.stack children=`子节点` slot=`槽` style=`样式`*
完成后返回*[调用 stack](layout.stack(children=`子节点`, slot=`槽`, style=`样式`))*。
## 分栏
| 参数 | 类型 | 说明 |
|------|------|------|
| 子节点 | list | 子块列表 |
| 槽 | text | 父区域名 |
| 样式 | text | 可选类名 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 子节点 | list | 必填 | 子块列表 |
| 槽 | text | "" | 父区域名 |
| 样式 | text | "" | 可选类名 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 父容器节点 |
这里使用`子节点`、`槽`=""、`样式`=""。
为 `子节点` 声明一层响应式多栏。默认 `槽`=""、`样式`=""。
父块只负责排列,内容和更深层结构留在导入的子组件。结果仍是 View 节点列表,
可以继续传给祖先组件或页面渲染,无需提前转为 HTML。
*> layout.columns children=`子节点` slot=`槽` style=`样式`*
完成后返回*[调用 columns](layout.columns(children=`子节点`, slot=`槽`, style=`样式`))*。
## 验收组件
| 参数 | 类型 | 说明 |
|------|------|------|
| 名 | text | 组件名称 |
| 职责 | text | 单一职责描述 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 名 | text | 必填 | 组件名称 |
| 职责 | text | 必填 | 单一职责描述 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 待人工或测试核对的清单 |
这里使用`名`、`职责`。
为 `名` 与 `职责` 返回待检查的条目。仅依据这两个文本无法证明组件合格,
所以结果明确标注为清单,调用者仍须检查文件内容与渲染结果,不自动发放通过标签。
*> layout.accept_component name=`名` duty=`职责`*
完成后返回*[调用 accept component](layout.accept_component(name=`名`, duty=`职责`))*。
+102 -84
View File
@@ -27,147 +27,165 @@ marqdo call ext/web/网页.mq.md 检视 '根="examples/web-layout-handbook"' --e
## 布局规则
与 `布局.规则` 相同,便于只打开本文件的智能体。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 布局规则映射 |
*> 布局.规则*
与 `布局.规则` 相同,便于只打开本文件的智能体。
完成后返回*[调用 规则](布局.规则())*。
## 页面
| 参数 | 类型 | 说明 |
|------|------|------|
| 标题 | text | 文档标题 |
| 路由 | text | 路径 |
| 方法 | text | HTTP 方法 |
| 正文 | text | Markdown 正文 |
| 节点 | any | View 表或 None |
| 数据源 | text | 表名 |
| 排序 | text | 如 -created_at |
| 条件 | text | col=val 列表 |
构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、
`节点`=None、`数据源`=""、`排序`=""、`条件`=""。站点页面优先用 `类型: 网页`
Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点必须是统一 View 表,
不是 HTML。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 标题 | text | "" | 文档标题 |
| 路由 | text | "/" | 路径 |
| 方法 | text | "GET" | HTTP 方法 |
| 正文 | text | "" | Markdown 正文 |
| 节点 | any | None | View 表或 None |
| 数据源 | text | "" | 表名 |
| 排序 | text | "" | 如 -created_at |
| 条件 | text | "" | col=val 列表 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 页面句柄 |
*> web.page title=`标题` route=`路由` method=`方法` body=`正文` nodes=`节点` data_source=`数据源` data_order=`排序` data_where=`条件`*
这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。
构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、
`节点`=None、`数据源`=""、`排序`=""、`条件`=""。站点页面优先用 `类型: 网页`
Artifact,由 `服务` 发现;本工具供预览或程序化构造。节点必须是统一 View 表,
不是 HTML。
完成后返回*[调用 page](web.page(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。
## 路由
| 参数 | 类型 | 说明 |
|------|------|------|
| 应用 | any | 应用句柄 |
| 路径 | text | URL 路径 |
| 方法 | text | HTTP 方法 |
| 页面 | any | Document 或 None |
| 函数 | text | Endpoint lib.member |
| 请求 | text | 请求体类型 |
| 响应 | text | 响应类型 |
| 鉴权 | text | 鉴权标签 |
在 `应用` 上注册已声明 Document 或 Endpoint:`路径`、`方法`="GET"、`页面`=None、
`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。不要隐式注册用户路由。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 应用 | any | 必填 | 应用句柄 |
| 路径 | text | 必填 | URL 路径 |
| 方法 | text | "GET" | HTTP 方法 |
| 页面 | any | None | Document 或 None |
| 函数 | text | "" | Endpoint lib.member |
| 请求 | text | "json" | 请求体类型 |
| 响应 | text | "json" | 响应类型 |
| 鉴权 | text | "" | 鉴权标签 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 路由结果 |
*> web.route app=`应用` path=`路径` method=`方法` page=`页面` fn=`函数` request=`请求` response=`响应` auth=`鉴权`*
这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。
在 `应用` 上注册已声明 Document 或 Endpoint:`路径`、`方法`="GET"、`页面`=None、
`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""。不要隐式注册用户路由。
完成后返回*[调用 route](web.route(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`))*。
## 渲染
| 参数 | 类型 | 说明 |
|------|------|------|
| 文档 | any | Document 或 None |
| 节点 | any | View 表或 None |
| 正文 | text | Markdown |
| 标题 | text | 标题 |
| 数据库 | any | 可选 db |
把 Document 或 View 节点渲染为 HTML(预览)。可选 `文档`=None、`节点`=None、
`正文`=""、`标题`=""、`数据库`=None。输入应来自 Markdown/View,而不是手写 HTML
大字符串。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 文档 | any | None | Document 或 None |
| 节点 | any | None | View 表或 None |
| 正文 | text | "" | Markdown |
| 标题 | text | "" | 调用方提供的标题 |
| 数据库 | any | None | 可选 db |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML 或渲染结果 |
*> web.render doc=`文档` nodes=`节点` body=`正文` title=`标题` db=`数据库`*
这里使用`文档`=None、`节点`=None、`正文`=""、`标题`=""、`数据库`=None。
把 Document 或 View 节点渲染为 HTML(预览)。可选 `文档`=None、`节点`=None、
`正文`=""、`标题`=""、`数据库`=None。输入应来自 Markdown/View,而不是手写 HTML
大字符串。
完成后返回*[调用 render](web.render(doc=`文档`, nodes=`节点`, body=`正文`, title=`标题`, db=`数据库`))*。
## 使用
| 参数 | 类型 | 说明 |
|------|------|------|
| 应用 | any | 应用句柄 |
| 中间件 | any | 中间件表 |
把 `中间件` 挂到 `应用`(表驱动)。禁止 `configure(...)` 垃圾抽屉。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 中间件 | any | 必填 | 中间件表 |
| 应用 | any | 必填 | 应用句柄 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 应用句柄 |
*> web.use app=`应用` middleware=`中间件`*
这里使用`中间件`、`应用`。
把 `中间件` 挂到 `应用`(表驱动)。禁止 `configure(...)` 垃圾抽屉。
完成后返回*[调用 use](web.use(app=`应用`, middleware=`中间件`))*。
## 检视
| 参数 | 类型 | 说明 |
|------|------|------|
| 应用 | any | 应用或 None |
| 根 | text | 离线扫描的站点目录 |
返回 `{declared, system}` 路由表;可选 `应用`=None。
可选 `根`="",给出时扫描站点目录,不启动服务器。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 应用 | any | None | 应用或 None |
| 根 | text | "" | 离线扫描的站点目录 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 路由检视 |
*> web.inspect app=`应用` root=`根`*
这里使用`应用`=None、`根`=""。
返回 `{declared, system}` 路由表;可选 `应用`=None。
可选 `根`="",给出时扫描站点目录,不启动服务器。
完成后返回*[调用 inspect](web.inspect(app=`应用`, root=`根`))*。
## 服务
| 参数 | 类型 | 说明 |
|------|------|------|
| 根 | text | 站点根目录 |
| 主机 | text | 绑定主机 |
| 端口 | number | 端口 |
| 数据库 | any | 可选 db |
| 静态目录 | text | 静态资源 |
| 中间件 | any | 可选中间件 |
扫描 `根`="." 下 `类型: 网页|端点` Artifact,注册声明路由并在 `主机`="127.0.0.1"
与 `端口`=18081 监听。可选 `数据库`=None、`静态目录`=""、`中间件`=None。站点
目录应已按布局铁律拆好组件文件。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 根 | text | "." | 站点根目录 |
| 主机 | text | "127.0.0.1" | 绑定主机 |
| 端口 | number | 18081 | 调用方提供的端口 |
| 数据库 | any | None | 可选 db |
| 静态目录 | text | "" | 静态资源 |
| 中间件 | any | None | 可选中间件 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 服务结果 |
*> web.serve root=`根` host=`主机` port=`端口` db=`数据库` static_dir=`静态目录` middleware=`中间件`*
这里使用`根`="."、`主机`="127.0.0.1"、`端口`=18081、`数据库`=None、`静态目录`=""、`中间件`=None。
扫描 `根`="." 下 `类型: 网页|端点` Artifact,注册声明路由并在 `主机`="127.0.0.1"
与 `端口`=18081 监听。可选 `数据库`=None、`静态目录`=""、`中间件`=None。站点
目录应已按布局铁律拆好组件文件。
完成后返回*[调用 serve](web.serve(root=`根`, host=`主机`, port=`端口`, db=`数据库`, static_dir=`静态目录`, middleware=`中间件`))*。
## 客户端挂载
| 参数 | 类型 | 说明 |
|------|------|------|
| 桥 | text | bridge 脚本路径 |
| wasm | text | wasm 路径 |
| 源 | text | 可选源 |
| 启动 | bool | 是否自动 boot |
嵌入 WASM 桥,默认 `桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、
`源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本路径 |
| wasm | text | "/static/marqdo_wasm.wasm" | wasm 路径 |
| 源 | text | "" | 可选源 |
| 启动 | bool | True | 是否自动 boot |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 挂载描述 |
*> web.client_embed bridge=`桥` wasm=`wasm` source=`源` boot=`启动`*
这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。
嵌入 WASM 桥,默认 `桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、
`源`=""、`启动`=True。不是用 HTML 字符串拼整页的借口。
完成后返回*[调用 client embed](web.client_embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。
+35 -28
View File
@@ -24,51 +24,58 @@ marqdo call ext/web/网页/客户端/索引.mq.md 文本补丁 '选择器="#stat
## 挂载
| 参数 | 类型 | 说明 |
|------|------|------|
| 桥 | text | bridge 脚本 URL |
| wasm | text | wasm URL |
| 源 | text | 可选源 |
| 启动 | bool | 自动启动 |
返回加载官方浏览器桥的 HTML 片段。默认 `桥`="/static/marqdo-bridge.js"、
`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。不是用 HTML 拼整页的
借口。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 桥 | text | "/static/marqdo-bridge.js" | bridge 脚本 URL |
| wasm | text | "/static/marqdo_wasm.wasm" | wasm URL |
| 源 | text | "" | 可选源 |
| 启动 | bool | True | 自动启动 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | script 标签 HTML |
*> client.embed bridge=`桥` wasm=`wasm` source=`源` boot=`启动`*
这里使用`桥`="/static/marqdo-bridge.js"、`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。
返回加载官方浏览器桥的 HTML 片段。默认 `桥`="/static/marqdo-bridge.js"、
`wasm`="/static/marqdo_wasm.wasm"、`源`=""、`启动`=True。不是用 HTML 拼整页的
借口。
完成后返回*[调用 embed](client.embed(bridge=`桥`, wasm=`wasm`, source=`源`, boot=`启动`))*。
## 文本补丁
| 参数 | 类型 | 说明 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 选择器 | text | 必填 | CSS 选择器 |
| 文本 | text | 必填 | 文本内容 |
| 返回 | 类型 | 说明 |
|------|------|------|
| 选择器 | text | CSS 选择器 |
| 文本 | text | 文本内容 |
| result | any | 效果表 |
这里使用`选择器`、`文本`。
为选择器 `选择器` 构造 `set_text` 效果表,文本为 `文本`。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 效果表 |
*> client.text_patch sel=`选择器` text=`文本`*
完成后返回*[调用 text patch](client.text_patch(sel=`选择器`, text=`文本`))*。
## 节点补丁
| 参数 | 类型 | 说明 |
|------|------|------|
| 选择器 | text | CSS 选择器 |
| html | text | 可选 HTML |
| 属性 | any | 可选属性表 |
| 移除 | bool | 是否移除 |
为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 选择器 | text | 必填 | CSS 选择器 |
| html | text | "" | 可选 HTML |
| 属性 | any | None | 可选属性表 |
| 移除 | bool | False | 是否移除 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 效果表 |
*> client.dom_patch sel=`选择器` html=`html` attrs=`属性` remove=`移除`*
这里使用`选择器`、`html`=""、`属性`=None、`移除`=False。
为选择器 `选择器` 构造 `dom` 效果表。可选 `html`=""、`属性`=None、`移除`=False。
完成后返回*[调用 dom patch](client.dom_patch(sel=`选择器`, html=`html`, attrs=`属性`, remove=`移除`))*。
+24 -18
View File
@@ -24,42 +24,48 @@ marqdo call ext/web/网页/文档对象模型/索引.mq.md 渲染 'dom=$body' --
## 自Markdown
| 参数 | 类型 | 说明 |
|------|------|------|
| 文本 | text | Markdown 源 |
把 Markdown `文本` 变成 `{kind:"markdown", text}`,供页面渲染。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 文本 | text | 必填 | Markdown 源 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | DOM 映射 |
*> dom.from_markdown text=`文本`*
这里使用`文本`。
把 Markdown `文本` 变成 `{kind:"markdown", text}`,供页面渲染。
完成后返回*[调用 from markdown](dom.from_markdown(text=`文本`))*。
## 原始
| 参数 | 类型 | 说明 |
|------|------|------|
| html | text | 原始 HTML |
逃逸舱 — 包装原始 `html`。仅当表驱动无法表达宿主约束时使用,并写明原因。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| html | text | 必填 | 原始 HTML |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | DOM 映射 kind=raw |
*> dom.raw html=`html`*
这里使用`html`。
逃逸舱 — 包装原始 `html`。仅当表驱动无法表达宿主约束时使用,并写明原因。
完成后返回*[调用 raw](dom.raw(html=`html`))*。
## 渲染
| 参数 | 类型 | 说明 |
|------|------|------|
| dom | any | 自Markdown 或 原始 的结果 |
把 DOM 映射 `dom` 渲染为 HTML(须插件)。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| dom | any | 必填 | 自Markdown 或 原始 的结果 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML 文本 |
*> dom.render dom=`dom`*
这里使用`dom`。
把 DOM 映射 `dom` 渲染为 HTML(须插件)。
完成后返回*[调用 render](dom.render(dom=`dom`))*。
+22 -12
View File
@@ -157,6 +157,12 @@ cargo test --locked --test gold ext_web -- --test-threads=1
返回建站流程与拆分终点,不执行文件操作,也不声称已经验收某个站点。
先建立区域树,再写父组件与 Markdown 叶子,最后按声明路由启动并测试。
这张表返回工程步骤与停止条件,供作者安排实现顺序;它不会自动创建目录、拆分现有页面或替站点完成验收。先确定区域树,把首页拆成导航、主体与页脚。若页脚有品牌栏和链接栏,再拆子区域;链接有文档与社区两栏时继续拆分。父文件只表达一层布局,叶子只保留可直接阅读的 Markdown 内容。
区域树稳定后,首页用 Document 元数据声明路由并选择装配入口。其他页面各自声明路由,接口逻辑放到 Endpoint,使请求期间的业务计算与启动时的页面装配各有归属。不要在返回组件的函数里启动服务器,也不要把启动时运行一次的装配误当作每次请求都会执行的数据绑定。
实现过程中先离线预览,核对实际父子节点和区域内容;再从站点目录启动服务,检查首页、普通文档和 API 的真实响应。浏览器还需验证宽屏分栏与窄屏折叠。只看清单文本、返回固定 ready 或将整页 HTML 分成几个字符串文件,都不能证明已实现统一的文档架构。若某个块仍需独立内部排列,就返回布局拆分阶段继续细化。
`workflow` =
| key | value |
@@ -171,7 +177,7 @@ cargo test --locked --test gold ext_web -- --test-threads=1
| step_G | compare preview and live output; test routes and browser geometry |
| stopping_rule | one Markdown responsibility and no internal layout |
*workflow*
完成后返回*workflow*。
## 布局规则
@@ -182,38 +188,42 @@ cargo test --locked --test gold ext_web -- --test-threads=1
复用布局模块的实践约定,保持一个真相源。无参数,不需要插件。
规则描述预期做法,实际站点仍需检查叶子、父关系与运行结果。
*> 布局.规则*
完成后返回*[调用 规则](布局.规则())*。
## 预览正文
| 参数 | 类型 | 说明 |
|------|------|------|
| 正文 | text | Markdown content |
| 标题 | text | Document title |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 正文 | text | "" | Markdown content |
| 标题 | text | "Preview" | Document title |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | HTML document |
这里使用`正文`=""、`标题`="Preview"。
离线渲染 Markdown `正文`="",默认 `标题`="Preview"。
此工具只返回 HTML 文本,不写文件、不注册路由。复杂页面先拆布局,
不要用整页原生 HTML 字符串冒充正文。需要原生插件。
*> 网页.渲染 正文=`正文` 标题=`标题`*
完成后返回*[调用 渲染](网页.渲染(正文=`正文`, 标题=`标题`))*。
## 预览节点
| 参数 | 类型 | 说明 |
|------|------|------|
| 节点 | list | Nested View rows |
| 标题 | text | Document title |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 节点 | list | 必填 | Nested View rows |
| 标题 | text | "Preview" | Document title |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | text | HTML document |
这里使用`节点`、`标题`="Preview"。
渲染已经按职责拆分的 `节点`,默认 `标题`="Preview"。
父节点的值继续持有子节点,叶子值为 Markdown;返回 HTML 不会启动服务。
与真实 Document 的装配使用同一渲染器,能检查双栏是否确实保留了层级。
*> 网页.渲染 节点=`节点` 标题=`标题`*
完成后返回*[调用 渲染](网页.渲染(节点=`节点`, 标题=`标题`))*。
+31 -23
View File
@@ -25,68 +25,76 @@ marqdo call ext/web/网页/组件/索引.mq.md 合并 '甲=[{"type":"text","valu
## 节点
| 参数 | 类型 | 说明 |
|------|------|------|
| 表 | any | View 表 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 表 | any | 必填 | View 表 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | Result |
| result | any | 原样返回输入 View 表,保留记录列表或列式表的实际形态 |
这里使用`表`。
原样返回 `表`,保留已有恒等入口。可接受列式表或记录列表;
需要组合和嵌套时统一选择 @ 记录列表,让子表保持结构值而不是字符串。
*> component.nodes table=`表`*
完成后返回*[调用 nodes](component.nodes(table=`表`))*。
## 合并
| 参数 | 类型 | 说明 |
|------|------|------|
| 甲 | list | 第一组节点记录 |
| 乙 | list | 第二组节点记录 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 甲 | list | 必填 | 第一组节点记录 |
| 乙 | list | 必填 | 第二组节点记录 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 有序兄弟节点 |
这里使用`甲`、`乙`。
拼接 `甲` 与 `乙`,保留顺序和内部父子关系。输入均为 @ 记录列表;
本工具不把平面节点变成两栏,需要双栏时再交给布局的分栏工具。
*> component.merge a=`甲` b=`乙`*
完成后返回*[调用 merge](component.merge(a=`甲`, b=`乙`))*。
## 正文
| 参数 | 类型 | 说明 |
|------|------|------|
| 文本 | text | 普通 Markdown |
| 槽 | text | 区域名 |
| 样式 | text | 可选类名 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 文本 | text | 必填 | 普通 Markdown |
| 槽 | text | "" | 区域名 |
| 样式 | text | "" | 可选类名 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 单个 Markdown 叶子 |
这里使用`文本`、`槽`=""、`样式`=""。
将 Markdown `文本` 包成叶子,默认 `槽`=""、`样式`=""。
不加载原生插件,输出仍为结构数据;标题、链接、列表与表格在渲染时处理。
叶子不关心自己位于页脚左栏还是其他位置,父组件负责几何关系。
*> component.markdown text=`文本` slot=`槽` style=`样式`*
完成后返回*[调用 markdown](component.markdown(text=`文本`, slot=`槽`, style=`样式`))*。
## 包裹
| 参数 | 类型 | 说明 |
|------|------|------|
| 子节点 | list | 子块记录列表 |
| 种类 | text | 容器类型 |
| 槽 | text | 区域名 |
| 样式 | text | 可选类名 |
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 子节点 | list | 必填 | 子块记录列表 |
| 种类 | text | "column" | 容器类型 |
| 槽 | text | "" | 区域名 |
| 样式 | text | "" | 可选类名 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | list | 包含子节点的父块 |
这里使用`子节点`、`种类`="column"、`槽`=""、`样式`=""。
将 `子节点` 放进一层父容器,默认 `种类`="column"、`槽`=""、`样式`=""。
几何类型为 row、column;语义类型包括 nav、header、footer、section、aside。
值单元格保留子表,不承载拼好的 HTML;构造器只生成结构,实际形状由渲染器检查。
*> component.wrap children=`子节点` kind=`种类` slot=`槽` style=`样式`*
完成后返回*[调用 wrap](component.wrap(children=`子节点`, kind=`种类`, slot=`槽`, style=`样式`))*。
+4 -4
View File
@@ -23,11 +23,11 @@ marqdo call ext/web/网页/能力/索引.mq.md 加载 --effects plugin --json
## 加载
通过 plugin.native_path 定位 ABI v2 web 动态库并 plugin.load。缺失时打印安装提
示并以非零退出。无参数。
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 加载成功后为空 |
*> cap.load*
通过 plugin.native_path 定位 ABI v2 web 动态库并 plugin.load。缺失时打印安装提
示并以非零退出。无参数。
完成后返回*[加载本操作依赖的原生插件](cap.load())*。
+37 -31
View File
@@ -24,54 +24,60 @@ marqdo call ext/web/网页/路由/索引.mq.md 注册 '路由=$route' --effects
## 新建
| 参数 | 类型 | 说明 |
|------|------|------|
| 应用 | any | 应用句柄 |
| 路径 | text | URL 路径 |
| 方法 | text | HTTP 方法 |
| 页面 | any | Document 或 None |
| 函数 | text | Endpoint 成员 |
| 请求 | text | 请求体类型 |
| 响应 | text | 响应类型 |
| 鉴权 | text | 鉴权标签 |
| 类别 | text | 路由类别 |
为 `应用` 在 `路径` 上构造路由句柄,`方法`="GET"。`页面`=None 或 `函数`="" 二
选一。`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。本工具尚未注册——再
调 `注册`,或用门面 `路由` 一步完成。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 应用 | any | 必填 | 应用句柄 |
| 路径 | text | 必填 | URL 路径 |
| 方法 | text | "GET" | HTTP 方法 |
| 页面 | any | None | Document 或 None |
| 函数 | text | "" | Endpoint 成员 |
| 请求 | text | "json" | 请求体类型 |
| 响应 | text | "json" | 响应类型 |
| 鉴权 | text | "" | 鉴权标签 |
| 类别 | text | "" | 路由类别 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 路由句柄 |
*> route.new app=`应用` path=`路径` method=`方法` page=`页面` fn=`函数` request=`请求` response=`响应` auth=`鉴权` class=`类别`*
这里使用`应用`、`路径`、`方法`="GET"、`页面`=None、`函数`=""、`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。
为 `应用` 在 `路径` 上构造路由句柄,`方法`="GET"。`页面`=None 或 `函数`="" 二
选一。`请求`="json"、`响应`="json"、`鉴权`=""、`类别`=""。本工具尚未注册——再
调 `注册`,或用门面 `路由` 一步完成。
完成后返回*[调用 new](route.new(app=`应用`, path=`路径`, method=`方法`, page=`页面`, fn=`函数`, request=`请求`, response=`响应`, auth=`鉴权`, class=`类别`))*。
## 注册
| 参数 | 类型 | 说明 |
|------|------|------|
| 路由 | any | 路由句柄 |
| 应用 | any | 应用或 None |
把路由句柄 `路由` 注册到应用;可选 `应用`=None 时用句柄内保存的应用。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路由 | any | 必填 | 路由句柄 |
| 应用 | any | None | 应用或 None |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 注册结果 |
*> route.register route=`路由` app=`应用`*
这里使用`路由`、`应用`=None。
把路由句柄 `路由` 注册到应用;可选 `应用`=None 时用句柄内保存的应用。
完成后返回*[调用 register](route.register(route=`路由`, app=`应用`))*。
## 使用
| 参数 | 类型 | 说明 |
|------|------|------|
| 路由 | any | 路由句柄 |
| 中间件 | any | 中间件表 |
给路由句柄 `路由` 挂上中间件表 `中间件`。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 路由 | any | 必填 | 路由句柄 |
| 中间件 | any | 必填 | 中间件表 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 结果 |
| result | any | 带 middleware 字段的路由记录;此步骤不注册或启动路由 |
*> route.use route=`路由` middleware=`中间件`*
这里使用`路由`、`中间件`。
给路由句柄 `路由` 挂上中间件表 `中间件`。
完成后返回*[调用 use](route.use(route=`路由`, middleware=`中间件`))*。
+28 -23
View File
@@ -24,39 +24,44 @@ marqdo call ext/web/网页/页面/索引.mq.md 渲染 '页面=$pg' --effects plu
## 新建
| 参数 | 类型 | 说明 |
|------|------|------|
| 标题 | text | 文档标题 |
| 路由 | text | 路径 |
| 方法 | text | HTTP 方法 |
| 正文 | text | Markdown 正文 |
| 节点 | any | View 表或 None |
| 数据源 | text | 表名 |
| 排序 | text | 排序键 |
| 条件 | text | 过滤 |
构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、
`节点`=None、`数据源`=""、`排序`=""、`条件`=""。节点必须是统一 View 表。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 标题 | text | "" | 文档标题 |
| 路由 | text | "/" | 路径 |
| 方法 | text | "GET" | HTTP 方法 |
| 正文 | text | "" | Markdown 正文 |
| 节点 | any | None | View 表或 None |
| 数据源 | text | "" | 表名 |
| 排序 | text | "" | 排序键 |
| 条件 | text | "" | 过滤 |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | 页面句柄 |
*> page.new title=`标题` route=`路由` method=`方法` body=`正文` nodes=`节点` data_source=`数据源` data_order=`排序` data_where=`条件`*
这里使用`标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、`节点`=None、`数据源`=""、`排序`=""、`条件`=""。
构造 Document 句柄,默认 `标题`=""、`路由`="/"、`方法`="GET"、`正文`=""、
`节点`=None、`数据源`=""、`排序`=""、`条件`=""。节点必须是统一 View 表。
完成后返回*[调用 new](page.new(title=`标题`, route=`路由`, method=`方法`, body=`正文`, nodes=`节点`, data_source=`数据源`, data_order=`排序`, data_where=`条件`))*。
## 渲染
| 参数 | 类型 | 说明 |
|------|------|------|
| 页面 | any | Document 句柄 |
| 节点 | any | View 表或 None |
| 数据库 | any | 可选 db |
渲染 Document 句柄 `页面`。可选 `节点`=None、`数据库`=None。不要把手写 HTML 当
作页面壳。
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| 页面 | any | 必填 | Document 句柄 |
| 节点 | any | None | View 表或 None |
| 数据库 | any | None | 可选 db |
| 返回 | 类型 | 说明 |
|------|------|------|
| result | any | HTML 或渲染结果 |
*> page.render page=`页面` nodes=`节点` db=`数据库`*
这里使用`页面`、`节点`=None、`数据库`=None。
渲染 Document 句柄 `页面`。可选 `节点`=None、`数据库`=None。不要把手写 HTML 当
作页面壳。
完成后返回*[调用 render](page.render(page=`页面`, nodes=`节点`, db=`数据库`))*。