fix(web): fail-fast when invoke lock is busy; document single-interp limit

Long sse-live chats held INVOKE_LOCK indefinitely and starved short routes
(UI freeze). Timed try-lock returns interpreter busy → HTTP 503; ADR 0008
records that HTTP is multi-goroutine while Marqdo evaluation stays single-flight.
Also lands plan/delta streaming and soft map guards used by qdagent chat.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-26 13:27:53 +08:00
1 parent b792f44556
commit 1b11fe063a
11 files changed
+838 -163

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
# ADR 0008:Web 热路径单解释器串行化(设计缺陷与缓解)
| | |
|---|---|
| Status | **Accepted**(缺陷已记录;缓解已落地;真并行未决) |
| Date | 2026-10-26 |
| Related | [web-invoke-serialization.md](../design/web-invoke-serialization.md) · ADR [0004](0004-web-plugin-go.md) · ADR [0007](0007-web-document-endpoint.md) · [ext-abi.md](../design/ext-abi.md) · [ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md) |
## Context
- Go `plugins/web` 的 HTTP 服务是**多 goroutine** 的:每个请求可并发进入 `handleInvoke` / `handleInvokeLiveSSE`。
- 每个 Endpoint 最终经 C ABI `host_query("call_lib_path", …)` 回到 Rust 宿主,在**同一个** `HostContext`(Marqdo 解释器状态)上执行作者 `.mq.md`。
- `HostContext` **不是** `Sync`:共享可变会话、库装载、写回、事件总线等状态不能安全地被多线程同时求值。
- 因此宿主用进程级 `INVOKE_LOCK`(`src/host/plugin.rs`)串行化所有来自 worker 线程的 `call_lib_path`。
### 常见误解
> 「web 都是单线程的吗?不能多线程吗?」
| 层 | 并发模型 |
|----|----------|
| Go HTTP / SSE flush / 取消 | **多线程(多 goroutine)** |
| Marqdo 解释器 `call_lib_path` | **单飞(一把全局锁)** |
| 浏览器 UI | 与后端锁无关;但若短 API 同步阻塞等待锁,会表现为「整页卡死」 |
**缺陷不在「HTTP 单线程」,而在「多 HTTP 工作线程共享一个非 Sync 解释器」。**
真并行需要多解释器实例(或可共享的隔离运行时),不是去掉 Go 侧并发。
### 事故形态(已观测)
长对话(`return=sse-live` / `stream:true`)在 `CallLibPath` 期间一直持有 `INVOKE_LOCK`。并发的短路由(如 `/v1/models`、设置页探测)在旧实现里对锁 **无限期** `lock()`,HTTP 挂起 → 前端 `fetch` 无超时 → 页面无响应。重启进程可恢复,但属于运维掩盖,不是正确错误处理。
## Decision
1. **承认并文档化**本限制为宿主架构缺陷(单 `HostContext` + 全局 `INVOKE_LOCK`),不得再被表述为「web 插件只能单线程」。
2. **缓解(已实现,非根治)**:
- `call_lib_path` 从 worker 进入时用 **限时 try-lock**(默认 `MARQDO_INVOKE_WAIT_MS=1500`),超时返回错误串 `interpreter busy: …`。
- Go `handleInvoke` 将含 `interpreter busy` 的错误映射为 **HTTP 503**,并设 `Retry-After: 2`。
- **禁止**在 SSE 期间把进程级 `MARQDO_INVOKE_WAIT_MS` 拉长:那会让并发短请求重新卡死。
- 长 SSE 在启动时用同一短预算争锁;一旦拿到则持有至调用结束(对话本来就要跑完)。
3. **客户端契约**:短 API 必须有超时与 503 文案;不得假设「任意时刻都能同步进入解释器」。
4. **根治(未决,另案)**:解释器池 / per-request isolate / 可 `Send` 的会话切片。未落地前,产品行为以本 ADR 的 503 语义为准。
## Consequences
### Positive
- 对话进行中,设置/模型列表等短请求约 1.5s 内失败并可读,UI 不再无限挂起。
- 缺陷有名有姓,后续多解释器工作不会被「修好了」的假象挡住。
### Negative / Risks
- 同一进程仍无法真正并行跑两个 Marqdo Endpoint 体;第二个长 SSE 也会在短预算后失败。
- 极短窗口内,短请求若正好撞上锁交接,可能偶发 503(可重试)。
- `MARQDO_INVOKE_WAIT_MS` 是进程环境变量;误设过大仍会复现卡顿。
### Neutral
- Go 多 goroutine、SSE 桥(`MARQDO_EVENT_FORWARD`)、取消令牌(`MARQDO_CANCEL_TOKEN`)保持不变。
- 不改变 Document / Endpoint 作者面(ADR 0007);只约束宿主与 web 插件错误语义。
## Implementation pointers
| 位置 | 职责 |
|------|------|
| `src/host/plugin.rs` → `acquire_invoke_lock` | 限时争锁;失败 `set_err("interpreter busy…")` |
| `plugins/web/.../routes_invoke.go` → `handleInvoke` | `interpreter busy` → 503 + `Retry-After` |
| 设计长文 | [web-invoke-serialization.md](../design/web-invoke-serialization.md) |
+161
View File
@@ -0,0 +1,161 @@
# Web 热路径:单解释器串行化(设计缺陷说明)
| | |
|---|---|
| 状态 | **Accepted**(缺陷记录 + 缓解已落地) |
| 日期 | 2026-10-26 |
| 规范决策 | [ADR 0008](../adr/0008-web-invoke-serialization.md) |
| 相关 | [ext-web-go-rewrite.md](ext-web-go-rewrite.md) · [ext-abi.md](ext-abi.md) · [ADR 0004](../adr/0004-web-plugin-go.md) · [ADR 0007](../adr/0007-web-document-endpoint.md) |
本文把「页面卡死 / 像单线程」拆成可验证的架构事实、错误语义与演进边界。
**结论先行:HTTP 是多线程的;卡住是因为所有 Endpoint 共享一把解释器锁。**
---
## 1. 问题陈述
### 1.1 用户可见症状
1. 发起一次长对话(OpenAI 兼容 `POST …/v1/chat/completions` + `stream:true` / `sse-live`)。
2. 对话尚未结束时,打开设置、拉 `/v1/models`、或其它短 JSON API。
3. **旧行为**:浏览器请求一直 pending,整页像死机;只能杀 `marqdo run serve…` 恢复。
4. **目标行为**:短请求在约 1.5s 内得到 **HTTP 503**,错误体标明 `interpreter busy`;对话 SSE 继续;结束后短请求立刻恢复 200。
### 1.2 错误归因(不要再说错)
| 错误说法 | 正确说法 |
|----------|----------|
| 「web 插件是单线程的」 | Go `net/http` 与 SSE 刷写是多 goroutine |
| 「忘记启动进程所以卡死」 | 进程在跑;是 **锁争用** 导致短请求永不返回 |
| 「把 SSE 的等待时间调大就能修好」 | 进程级拉长 `MARQDO_INVOKE_WAIT_MS` 会让短请求一起卡死 |
| 「去掉 INVOKE_LOCK 即可并行」 | `HostContext` 非 Sync,无锁并行会数据竞争 / 未定义行为 |
---
## 2. 调用栈与锁边界
```
Browser
│ GET /v1/models POST /v1/chat/completions (SSE)
▼
Go plugins/web (多 goroutine)
handleInvoke / handleInvokeLiveSSE
│
▼ C ABI host_query("call_lib_path", {path, args})
Rust src/host/plugin.rs
┌─────────────────────────────┐
│ INVOKE_LOCK (进程级 Mutex) │ ← 同一时刻只允许一个 worker 进入
└─────────────────────────────┘
│
▼
HostContext:装载/求值作者 .mq.md、写回、事件总线、LLM 插件回调…
```
要点:
1. **锁在宿主,不在 Go 业务路由表。** 增加更多 Go handler 不会自动并行执行 Marqdo。
2. **SSE 持锁时间 ≈ 整次 Endpoint 求值时间**(含多次 LLM 往返),可达数十秒到数分钟。
3. **事件转发**(`MARQDO_EVENT_FORWARD` NDJSON)与 **取消**(`MARQDO_CANCEL_TOKEN`)在持锁期间仍可由其它 goroutine 写文件/读桥;它们不进入解释器,故不受 `INVOKE_LOCK` 保护,也不应误设长等待。
---
## 3. 为何不能简单「多线程跑 Marqdo」
`HostContext` 持有(非穷尽):
- 当前模块图、函数表、写回缓冲与 FS 根;
- 插件注册与 `CURRENT_HOST` / 全局 host 指针;
- Agent / LLM 运行时与 stream 发布钩子;
- 与文档写回、会话态相关的可变结构。
这些状态在实现上按**单线程求值**建模。把它标成 `Sync` 或去掉 `INVOKE_LOCK` 而没有隔离运行时,属于未定义行为,不是性能优化。
**真并行的合法方向(未实现):**
1. **解释器池**:每请求或每会话一个 `HostContext`(或可重置的 isolate),路由层选闲置实例;
2. **只读快照 + 写队列**:热路径只读克隆,写回串行合并(适合纯查询 Endpoint,不适合带写回的 agent);
3. **把长任务移出解释器**:Marqdo 只做编排,重活在独立进程/队列(与「代码即文档」主路径权衡后再定)。
在上述任一方案落地并经金样例验收前,**产品必须以「单飞解释器」为约束设计 UX**。
---
## 4. 缓解契约(已实现)
### 4.1 宿主:限时争锁
文件:`src/host/plugin.rs`
- 仅当从 worker 线程进入(`CURRENT_HOST` 为空、走全局 host)时争 `INVOKE_LOCK`。
- `acquire_invoke_lock`:`try_lock` 循环,预算默认 **1500ms**(`MARQDO_INVOKE_WAIT_MS`,最小 1)。
- 超时:`set_err("interpreter busy: another request holds the Marqdo invoke lock (waited …ms)")`,返回非 0。
- **不要**在 SSE 入口把该环境变量设成数分钟:它是进程级的,会污染并发短请求。
### 4.2 Web 插件:503
文件:`plugins/web/internal/httpx/routes_invoke.go`
- 普通 JSON invoke:错误信息含 `interpreter busy` → **503** + `Retry-After: 2` + `{ok:false, error:…}`。
- Live SSE:若启动时即 busy,以失败事件/错误结束该流,**不得**无限挂起握手。
### 4.3 客户端:超时与文案
短 API(模型列表、设置、registry 探测等)必须:
- 设置合理 `fetch` 超时(秒级,例如 8s);
- 将 503 / `interpreter busy` 展示为「服务正忙(对话进行中)」类可读提示,而不是空白转圈。
(qdagent 前端 `frontend/src/lib/api.ts` 已按此契约处理。)
### 4.4 验收探针
在本地 serve 上:
```bash
# 终端 A:启动长 SSE 对话(持锁)
curl -N -m 120 -H 'Authorization: Bearer …' -H 'Content-Type: application/json' \
-d '{"stream":true,…}' http://127.0.0.1:PORT/v1/chat/completions
# 终端 B:对话进行中
curl -sS -w 'http=%{http_code} time=%{time_total}\n' --max-time 5 \
-H 'Authorization: Bearer …' http://127.0.0.1:PORT/v1/models
# 期望:http=503,time≈1.5,body 含 interpreter busy
# 对话结束后再打同一 URL → http=200,time≪1s
```
---
## 5. 运维与调参
| 变量 | 默认 | 含义 |
|------|------|------|
| `MARQDO_INVOKE_WAIT_MS` | `1500` | worker 进入解释器前最长等待;超时 → busy |
建议:
- 开发机 / 产品默认保持 1–3s。
- **禁止**为「让第二个聊天排队」而把默认调到分钟级——那等于恢复卡死。
- 需要排队时,应在 **应用层**(会话队列、UI 禁用「再发一条」),而不是拉长宿主锁等待。
---
## 6. 与其它机制的边界
| 机制 | 与 INVOKE_LOCK 的关系 |
|------|----------------------|
| `MARQDO_EVENT_FORWARD` | SSE 期间写 NDJSON;不替代争锁;不延长等待 |
| `MARQDO_CANCEL_TOKEN` | 断开连接时可取消 LLM;释放锁仍取决于解释器何时回到 FFI |
| `web.serve` / 静态资源 | 通常不经 `call_lib_path`,不受本锁影响 |
| 插件内部 Tokio/Go 并发 | 可以;只要不再次 `call_lib_path` 进同一 HostContext |
---
## 7. 演进检查清单(根治前勿宣称「已支持并行 Endpoint」)
- [ ] 多 `HostContext` 或 isolate 的生命周期与 ABI(装载、shutdown、写回冲突)有设计稿与金样例。
- [ ] 池化后 `call_lib_path` 不再依赖进程级单锁,或锁粒度降到实例级。
- [ ] 两个并发长 SSE + 一个短 `/v1/models` 的压力测试:短请求稳定 200,长请求互不污染会话写回。
- [ ] 更新本文件与 ADR 0008 Status(例如改为 Superseded by ADR NNNN)。
在清单完成前,对外与文档中应明确:**Marqdo Web Endpoint 求值在单进程内串行;HTTP 层并发,解释器层单飞。**
+307 -140
View File
@@ -8,6 +8,7 @@ import:
sys: lib/sys.mq.md
fs: lib/fs.mq.md
time: lib/time.mq.md
text: lib/text.mq.md
wb: lib/writeback.mq.md
subtask: lib/subtask.mq.md
plugin: lib/plugin.mq.md
@@ -58,30 +59,45 @@ The runbook `.mq.md` is ground truth (code as documentation). Default budgets ke
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
One LLM turn via the semantic surface (`ask` / `stream`+`collect`). Returns `{text,llm_calls,tokens}` for episode metrics; transport failures set `error` + `llm_calls=0` (never abort).
`stream_kind=plan` publishes protocol tokens onto the process trail (not the answer bubble).
1. `stream`
**evs = > model.stream prompt=`prompt` echo=`echo`**
**evs = > model.stream prompt=`prompt` echo=`echo` stream_kind=`stream_kind`**
**text = > llm.collect events=`evs`**
**tokens = None**
**tokens = 0**
**err = None**
**calls = 1**
1. not `text`
**e0 = > at value=`evs` index=0**
**err = > json.get value=`e0` key="message"**
1. `err`
**calls = 0**
**e0_s = > json.stringify value=`e0`**
**e0_map = > text.starts_with text=`e0_s` prefix="{"**
1. `e0_map`
**err = > json.get value=`e0` key="message"**
1. `err`
**calls = 0**
2. *
**_ = 1**
2. *
**r = > model.ask prompt=`prompt`**
**text = > json.get value=`r` key="text"**
**tokens = > json.get value=`r` key="tokens"**
**err = > json.get value=`r` key="error"**
**fin = > json.get value=`r` key="finish"**
1. `tokens`
**_ = 1**
**r_s = > json.stringify value=`r`**
**r_map = > text.starts_with text=`r_s` prefix="{"**
1. `r_map`
**text = > json.get value=`r` key="text"**
**tokens = > json.get value=`r` key="tokens"**
**err = > json.get value=`r` key="error"**
**fin = > json.get value=`r` key="finish"**
2. *
**tokens = None**
**text = > str value=`r`**
**tokens = 0**
**err = None**
**fin = None**
1. not `tokens`
**tokens = 0**
2. *
**_ = 1**
1. `err`
**calls = 0**
2. `fin` == "error"
@@ -183,7 +199,7 @@ Allowlist check, then invoke the runbook `##` via `lib/subtask` (`spawn fn=` →
Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer.
**q = > json.quote text=`goal`**
**esc = > json.parse text={"h":"---\ntitle: agent workbook\nimport:\n llm: ext/ai/llm.mq.md\n agent: ext/ai/agent.mq.md\n json: lib/json.mq.md\n sys: lib/sys.mq.md\n wb: lib/writeback.mq.md\n subtask: lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u002a\u0060model\u0060 = > llm.create model=\u0060sys.env_get name=\"OPENAI_MODEL\"\u0060 base_url=\u0060sys.env_get name=\"OPENAI_BASE_URL\"\u0060 backend=openai name=workbook\u002a\u002a\n","s2":"\u002a\u002a\u0060tools\u0060 = > table.empty_list\u002a\u002a\n","s3":"\u002a\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools.\u002a\u002a\n","s4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"}\u002a\u002a\n","s6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task\u002a\u002a\n","s7":"\u002a\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=False\u002a\u002a\n","s7b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result\u002a\u002a\n","s8":"\u002a\u002a\u0060text\u0060\u002a\u002a\n","d3":"\u002a\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You gather facts for the goal. Be concise. Do not invent tools.\u002a\u002a\n","d3b":"\u002a\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You write the final answer from research notes. Do not invent tools.\u002a\u002a\n","d4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"}\u002a\u002a\n","d6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task\u002a\u002a\n","d7":"\u002a\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=False\u002a\u002a\n","d8":"\u002a\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060\u002a\u002a\n","d9":"\u002a\u002a\u0060wt\u0060 = Write the final answer. Research notes:\u002a\u002a\n","d10":"\u002a\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060\u002a\u002a\n","d11":"\u002a\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=False\u002a\u002a\n","d11b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result\u002a\u002a\n","d12":"\u002a\u002a\u0060text\u0060\u002a\u002a\n"}**
**esc = > json.parse text={"h":"---\ntitle: agent workbook\nimport:\n llm: ext/ai/llm.mq.md\n agent: ext/ai/agent.mq.md\n json: lib/json.mq.md\n sys: lib/sys.mq.md\n table: lib/table.mq.md\n wb: lib/writeback.mq.md\n subtask: lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u002a\u0060env_model\u0060 = > sys.env_get name=\"OPENAI_MODEL\"\u002a\u002a\n\u002a\u002a\u0060env_base\u0060 = > sys.env_get name=\"OPENAI_BASE_URL\"\u002a\u002a\n\u002a\u002a\u0060env_key\u0060 = > sys.env_get name=\"OPENAI_API_KEY\"\u002a\u002a\n\u002a\u002a\u0060model\u0060 = > llm.create model=\u0060env_model\u0060 base_url=\u0060env_base\u0060 api_key=\u0060env_key\u0060 backend=\"openai-compatible\" name=\"workbook\"\u002a\u002a\n","s2":"\u002a\u002a\u0060tools\u0060 = > table.empty_list\u002a\u002a\n","s3":"\u002a\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools.\"\u002a\u002a\n","s4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"}\u002a\u002a\n","s6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=\"task\"\u002a\u002a\n","s7":"\u002a\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","s7b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=\"result\"\u002a\u002a\n","s8":"\u002a\u0060text\u0060\u002a\n","d3":"\u002a\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You gather facts for the goal. Be concise. Do not invent tools.\"\u002a\u002a\n","d3b":"\u002a\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=\"You write the final answer from research notes. Do not invent tools.\"\u002a\u002a\n","d4":"\u002a\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"}\u002a\u002a\n","d6":"\u002a\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=\"task\"\u002a\u002a\n","d7":"\u002a\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=True\u002a\u002a\n","d8":"\u002a\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060\u002a\u002a\n","d9":"\u002a\u002a\u0060wt\u0060 = \"Write the final answer. Research notes:\"\u002a\u002a\n","d10":"\u002a\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060\u002a\u002a\n","d11":"\u002a\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=True\u002a\u002a\n","d11b":"\u002a\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=\"result\"\u002a\u002a\n","d12":"\u002a\u0060text\u0060\u002a\n"}**
**h = > json.get value=`esc` key="h"**
**s1 = > json.get value=`esc` key="s1"**
**s2 = > json.get value=`esc` key="s2"**
@@ -1080,8 +1096,15 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
*> lib_catalog*
4. `name` == scratch_tool_write
**parsed = > extract_scratch_tool reply=`reply`**
**tn = > json.get value=`parsed` key="name"**
**tt = > json.get value=`parsed` key="text"**
**parsed_s = > json.stringify value=`parsed`**
**parsed_map = > text.starts_with text=`parsed_s` prefix="{"**
**tn = None**
**tt = None**
1. `parsed_map`
**tn = > json.get value=`parsed` key="name"**
**tt = > json.get value=`parsed` key="text"**
2. *
**_ = 1**
**errs = > json.parse text={"a":"scratch_tool_write needs NAME line and fenced body","b":"scratch_tool_write needs NAME id"}**
1. `tn`
1. `tt`
@@ -1092,9 +1115,17 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
*> json.get value=`errs` key="b"*
5. `name` == corpus_search
**args = > extract_call_args reply=`reply`**
**q = > json.get value=`args` key="query"**
**root = > json.get value=`args` key="root"**
**limit = > json.get value=`args` key="limit"**
**args_s = > json.stringify value=`args`**
**args_map = > text.starts_with text=`args_s` prefix="{"**
**q = None**
**root = None**
**limit = None**
1. `args_map`
**q = > json.get value=`args` key="query"**
**root = > json.get value=`args` key="root"**
**limit = > json.get value=`args` key="limit"**
2. *
**_ = 1**
**cerrs = > json.parse text={"q":"corpus_search needs ARGS.query"}**
1. not `q`
*> json.get value=`cerrs` key="q"*
@@ -1109,7 +1140,13 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
*> corpus_search query=`q`*
6. `name` == mcp_list_tools
**args = > extract_call_args reply=`reply`**
**fx = > json.get value=`args` key="fixture"**
**args_s = > json.stringify value=`args`**
**args_map = > text.starts_with text=`args_s` prefix="{"**
**fx = None**
1. `args_map`
**fx = > json.get value=`args` key="fixture"**
2. *
**_ = 1**
**merrs = > json.parse text={"f":"mcp_list_tools needs ARGS.fixture"}**
1. `fx`
*> mcp_list_tools fixture=`fx`*
@@ -1117,9 +1154,17 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
*> json.get value=`merrs` key="f"*
7. `name` == mcp_call
**args = > extract_call_args reply=`reply`**
**fx = > json.get value=`args` key="fixture"**
**tn = > json.get value=`args` key="name"**
**targ = > json.get value=`args` key="arguments"**
**args_s = > json.stringify value=`args`**
**args_map = > text.starts_with text=`args_s` prefix="{"**
**fx = None**
**tn = None**
**targ = None**
1. `args_map`
**fx = > json.get value=`args` key="fixture"**
**tn = > json.get value=`args` key="name"**
**targ = > json.get value=`args` key="arguments"**
2. *
**_ = 1**
**xerrs = > json.parse text={"f":"mcp_call needs ARGS.fixture","n":"mcp_call needs ARGS.name"}**
1. `fx`
1. `tn`
@@ -1180,14 +1225,28 @@ Parent Plan-and-Move tools (helpers + whitelist `CALL:lib…`).
+ `observation`
Bounded observation for the parent prompt (actionable, short).
Tolerates missing/non-map observation (empty compact) instead of `json get needs map`.
Map check via stringify prefix `{` — never hard-get on None / bare text / list.
**obs_path = > json.get value=`observation` key="path"**
**obs_code = > json.get value=`observation` key="exit_code"**
**obs_val = > json.get value=`observation` key="value"**
**obs_slots = > json.get value=`observation` key="slots"**
**obs_src = > json.get value=`observation` key="source"**
**obs_stdout = > json.get value=`observation` key="stdout"**
**obs_stderr = > json.get value=`observation` key="stderr"**
**obs_path = None**
**obs_code = None**
**obs_val = None**
**obs_slots = None**
**obs_src = None**
**obs_stdout = None**
**obs_stderr = None**
**obs_s = > json.stringify value=`observation`**
**obs_map = > text.starts_with text=`obs_s` prefix="{"**
1. `obs_map`
**obs_path = > json.get value=`observation` key="path"**
**obs_code = > json.get value=`observation` key="exit_code"**
**obs_val = > json.get value=`observation` key="value"**
**obs_slots = > json.get value=`observation` key="slots"**
**obs_src = > json.get value=`observation` key="source"**
**obs_stdout = > json.get value=`observation` key="stdout"**
**obs_stderr = > json.get value=`observation` key="stderr"**
2. *
**_ = 1**
**src_len = 0**
**has_step = False**
1. `obs_src`
@@ -1207,97 +1266,102 @@ Bounded observation for the parent prompt (actionable, short).
|------|------|-----------|------------|-----------------|------------------|
| Plan-and-Move: CALL/READ then DECISION. Success (exit 0 + has_value) → DONE. solidify_on_done. No long prose. | `obs_path` | `obs_code` | `src_len` | `has_step` | True |
1. `obs_src`
**ex = > json.get value=`observation` key="source_excerpt"**
1. `ex`
**compact = table.put in=`compact` at="source_excerpt" value=`ex`**
1. `obs_map`
1. `obs_src`
**ex = > json.get value=`observation` key="source_excerpt"**
1. `ex`
**compact = table.put in=`compact` at="source_excerpt" value=`ex`**
2. *
**ex = > workbook_source_excerpt source=`obs_src`**
**compact = table.put in=`compact` at="source_excerpt" value=`ex`**
2. *
**ex = > workbook_source_excerpt source=`obs_src`**
**compact = table.put in=`compact` at="source_excerpt" value=`ex`**
2. *
**_ = 1**
**_ = 1**
1. `obs_stderr`
**tail = > json.get value=`observation` key="stderr_tail"**
1. `tail`
**compact = table.put in=`compact` at="stderr_tail" value=`tail`**
1. `obs_stderr`
**tail = > json.get value=`observation` key="stderr_tail"**
1. `tail`
**compact = table.put in=`compact` at="stderr_tail" value=`tail`**
2. *
**tail = > text_tail_lines text=`obs_stderr`**
**compact = table.put in=`compact` at="stderr_tail" value=`tail`**
2. *
**tail = > text_tail_lines text=`obs_stderr`**
**compact = table.put in=`compact` at="stderr_tail" value=`tail`**
2. *
**_ = 1**
1. `obs_stdout`
**tail = > json.get value=`observation` key="stdout_tail"**
1. `tail`
**compact = table.put in=`compact` at="stdout_tail" value=`tail`**
**_ = 1**
1. `obs_stdout`
**tail = > json.get value=`observation` key="stdout_tail"**
1. `tail`
**compact = table.put in=`compact` at="stdout_tail" value=`tail`**
2. *
**tail = > text_tail_lines text=`obs_stdout`**
**compact = table.put in=`compact` at="stdout_tail" value=`tail`**
2. *
**tail = > text_tail_lines text=`obs_stdout`**
**compact = table.put in=`compact` at="stdout_tail" value=`tail`**
2. *
**_ = 1**
**_ = 1**
**val_txt = > str value=`obs_val`**
**val_len = > len value=`val_txt`**
1. `obs_val`
**compact = table.put in=`compact` at="has_value" value=True**
**compact = table.put in=`compact` at="value_len" value=`val_len`**
1. `val_len` > 200
**preview = > text_head_lines text=`val_txt` max_lines=4 max_chars=200**
**compact = table.put in=`compact` at="value_preview" value=`preview`**
**val_txt = > str value=`obs_val`**
**val_len = > len value=`val_txt`**
1. `obs_val`
**compact = table.put in=`compact` at="has_value" value=True**
**compact = table.put in=`compact` at="value_len" value=`val_len`**
1. `val_len` > 200
**preview = > text_head_lines text=`val_txt` max_lines=4 max_chars=200**
**compact = table.put in=`compact` at="value_preview" value=`preview`**
2. *
**compact = table.put in=`compact` at="value" value=`obs_val`**
2. *
**compact = table.put in=`compact` at="value" value=`obs_val`**
**compact = table.put in=`compact` at="has_value" value=False**
**slots_brief = > table.empty_list**
1. `obs_slots`
- [slot](遍历 `obs_slots` 为 `slot`)
**sk = > json.get value=`slot` key="key"**
**sl = > json.get value=`slot` key="line"**
**sb = > json.get value=`slot` key="body"**
**sb_txt = > str value=`sb`**
**sb_len = > len value=`sb_txt`**
`brief` =
| key | line | body_len |
|-----|------|----------|
| `sk` | `sl` | `sb_len` |
1. `sk` == error
**prev = > text_head_lines text=`sb_txt` max_lines=8 max_chars=400**
**brief = table.put in=`brief` at="body_preview" value=`prev`**
2. *
**_ = 1**
**slots_brief = > table.append list=`slots_brief` item=`brief`**
2. *
**_ = 1**
**compact = table.put in=`compact` at="slots" value=`slots_brief`**
**detail = > json.get value=`observation` key="slots_detail"**
1. `detail`
**compact = table.put in=`compact` at="slots_detail" value=`detail`**
2. *
**_ = 1**
**tool_result = > json.get value=`observation` key="tool_result"**
1. `tool_result`
**tr = > str value=`tool_result`**
**tr = > text_head_lines text=`tr` max_lines=40 max_chars=3000**
**compact = table.put in=`compact` at="tool_result" value=`tr`**
2. *
**_ = 1**
**last_error = > json.get value=`observation` key="last_error"**
1. `last_error`
**err_txt = > str value=`last_error`**
**err_len = > len value=`err_txt`**
1. `err_len` > 200
**prev = > text_head_lines text=`err_txt` max_lines=8 max_chars=400**
**compact = table.put in=`compact` at="last_error_preview" value=`prev`**
**compact = table.put in=`compact` at="last_error_len" value=`err_len`**
2. *
**compact = table.put in=`compact` at="last_error" value=`last_error`**
2. *
**_ = 1**
2. *
**compact = table.put in=`compact` at="has_value" value=False**
**slots_brief = > table.empty_list**
1. `obs_slots`
- [slot](遍历 `obs_slots` 为 `slot`)
**sk = > json.get value=`slot` key="key"**
**sl = > json.get value=`slot` key="line"**
**sb = > json.get value=`slot` key="body"**
**sb_txt = > str value=`sb`**
**sb_len = > len value=`sb_txt`**
`brief` =
| key | line | body_len |
|-----|------|----------|
| `sk` | `sl` | `sb_len` |
1. `sk` == error
**prev = > text_head_lines text=`sb_txt` max_lines=8 max_chars=400**
**brief = table.put in=`brief` at="body_preview" value=`prev`**
2. *
**_ = 1**
**slots_brief = > table.append list=`slots_brief` item=`brief`**
2. *
**_ = 1**
**compact = table.put in=`compact` at="slots" value=`slots_brief`**
**detail = > json.get value=`observation` key="slots_detail"**
1. `detail`
**compact = table.put in=`compact` at="slots_detail" value=`detail`**
2. *
**_ = 1**
**tool_result = > json.get value=`observation` key="tool_result"**
1. `tool_result`
**tr = > str value=`tool_result`**
**tr = > text_head_lines text=`tr` max_lines=40 max_chars=3000**
**compact = table.put in=`compact` at="tool_result" value=`tr`**
2. *
**_ = 1**
**last_error = > json.get value=`observation` key="last_error"**
1. `last_error`
**err_txt = > str value=`last_error`**
**err_len = > len value=`err_txt`**
1. `err_len` > 200
**prev = > text_head_lines text=`err_txt` max_lines=8 max_chars=400**
**compact = table.put in=`compact` at="last_error_preview" value=`prev`**
**compact = table.put in=`compact` at="last_error_len" value=`err_len`**
2. *
**compact = table.put in=`compact` at="last_error" value=`last_error`**
2. *
**_ = 1**
**empty_slots = > table.empty_list**
**compact = table.put in=`compact` at="slots" value=`empty_slots`**
*compact*
@@ -1351,6 +1415,14 @@ First matching DECISION / 决定 line wins (ignore later conflicting decisions i
2. *
**_ = 1**
1. `found`
Take the first token only (`DECISION: RUN please` → RUN).
**toks = > split value=`found` sep=" "**
**found = > at value=`toks` index=0**
**found = > trim value=`found`**
2. *
**_ = 1**
1. `found` == DONE
*"DONE"*
2. `found` == CONTINUE
@@ -1371,8 +1443,17 @@ First matching DECISION / 决定 line wins (ignore later conflicting decisions i
*"REUSE"*
10. `found` == 新建
*"NEW"*
11. *
*found*
11. `found` == PATCH
Models sometimes invent `DECISION: PATCH` — treat as CONTINUE.
*"CONTINUE"*
12. *
If the reply carries a FIND/REPLACE block, treat unknown labels as CONTINUE.
**has_find = > split value=`text` sep="<<<"**
**n_find = > len value=`has_find`**
1. `n_find` > 1
*"CONTINUE"*
2. *
*found*
---
@@ -1544,7 +1625,13 @@ Parent Plan-and-Move prompt. Short protocol only — no long monologues.
2. *
**up = None**
**skill_from_obs = > json.get value=`observation` key="skill_brief"**
**skill_from_obs = None**
**obs_probe = > json.stringify value=`observation`**
**obs_is_map = > text.starts_with text=`obs_probe` prefix="{"**
1. `obs_is_map`
**skill_from_obs = > json.get value=`observation` key="skill_brief"**
2. *
**_ = 1**
1. `skill_from_obs`
**skill = skill_from_obs**
2. *
@@ -1612,22 +1699,20 @@ LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,event
**left = 0**
3. *
**ctx = > build_plan_context agent=`agent` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=`phase`**
Plan protocol streams as `stream_kind=plan` (process trail). Answer tokens
still come from workbook `worker.step stream=True` (`stream_kind=delta`).
1. `stream`
**evs = > model.stream prompt=`ctx` echo=`echo`**
**last_reply = > llm.collect events=`evs`**
**evs_all = > plan_merge_deltas events=`evs_all` from=`evs` stream=`stream`**
**e0 = > at value=`evs` index=0**
**terr = > json.get value=`e0` key="message"**
**etype = > json.get value=`e0` key="type"**
1. `etype` == "error"
**transport_err = `terr`**
1. not `transport_err`
**transport_err = "llm stream transport error"**
**left = 0**
2. *
**llm_calls = llm_calls + 1**
**turn = > model_turn model=`model` prompt=`ctx` stream=True echo=`echo` stream_kind="plan"**
2. *
**turn = > model_turn model=`model` prompt=`ctx` stream=False echo=`echo`**
**turn_s = > json.stringify value=`turn`**
**turn_map = > text.starts_with text=`turn_s` prefix="{"**
**terr = None**
**last_reply = ""**
1. not `turn_map`
**transport_err = "model_turn_not_map"**
**left = 0**
2. *
**terr = > json.get value=`turn` key="error"**
1. `terr`
**transport_err = `terr`**
@@ -1636,6 +1721,14 @@ LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,event
**last_reply = > json.get value=`turn` key="text"**
**c = > json.get value=`turn` key="llm_calls"**
**t = > json.get value=`turn` key="tokens"**
1. not `c`
**c = 0**
2. *
**_ = 1**
1. not `t`
**t = 0**
2. *
**_ = 1**
**llm_calls = llm_calls + c**
**tokens = tokens + t**
1. `transport_err`
@@ -1643,16 +1736,49 @@ LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,event
**last_reply = `transport_err`**
**left = 0**
2. *
**last_reply = > trim value=`last_reply`**
**act = > extract_plan_act reply=`last_reply`**
**kind = > json.get value=`act` key="kind"**
**name = > json.get value=`act` key="name"**
1. not `last_reply`
**last_reply = ""**
2. *
**last_reply = > trim value=`last_reply`**
Plan replies often embed CALL: inside PATCH bodies — prefer an explicit
DECISION line when present so protocol exit is not stolen by a false CALL.
**dec_line = > extract_plan_decision reply=`last_reply`**
**kind = "unknown"**
**name = None**
1. `dec_line`
**kind = "decision"**
**name = `dec_line`**
2. *
**act = > extract_plan_act reply=`last_reply`**
**act_s = > json.stringify value=`act`**
**act_map = > text.starts_with text=`act_s` prefix="{"**
1. `act_map`
**kind = > json.get value=`act` key="kind"**
**name = > json.get value=`act` key="name"**
2. *
**_ = 1**
Live act marker so the UI never goes silent between plan tokens and the next step.
1. `stream`
`act_ev` =
| type | kind | name |
|------|------|------|
| plan_act | `kind` | `name` |
> sys.stream_publish event=`act_ev`
2. *
**_ = 1**
1. `kind` == call
**evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="call" stream=`stream`**
**tool_out = > run_parent_tool name=`name` path=`path` observation=`last_obs` reply=`last_reply`**
**brief = > tool_result_brief value=`tool_out`**
**evs_all = > plan_append_tool events=`evs_all` type="tool_end" name=`name` kind="call" result=`brief` stream=`stream`**
**last_obs = table.put in=`last_obs` at="tool_result" value=`tool_out`**
**obs_s = > json.stringify value=`last_obs`**
**obs_map = > text.starts_with text=`obs_s` prefix="{"**
1. `obs_map`
**last_obs = table.put in=`last_obs` at="tool_result" value=`tool_out`**
2. *
**_ = 1**
**left = left - 1**
2. `kind` == read
**evs_all = > plan_append_tool events=`evs_all` type="tool_start" name=`name` kind="read" stream=`stream`**
@@ -2103,6 +2229,12 @@ Primary author entry (v2 + P4): Adaptive `route` → execute (policy/kb skill) o
| ok | `task` | `child_val` | `path` | hit | `rmode` | `sk` | `last_obs` | adaptive route hit | `routed` |
**llm_calls = 0**
1. `stream`
**_ev = > table.empty_list**
**_ev = > plan_append_decision events=`_ev` decision="REUSE" stream=True summary="adaptive route hit"**
**_ev = > plan_append_round events=`_ev` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=True**
2. *
**_ = 1**
2. *
**route_matched = False**
2. *
@@ -2341,6 +2473,14 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
**reply = > json.get value=`turn` key="text"**
**c = > json.get value=`turn` key="llm_calls"**
**t = > json.get value=`turn` key="tokens"**
1. not `c`
**c = 0**
2. *
**_ = 1**
1. not `t`
**t = 0**
2. *
**_ = 1**
**llm_calls = llm_calls + c**
**tokens = tokens + t**
**reply = > trim value=`reply`**
@@ -2393,6 +2533,14 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
**reply = > json.get value=`turn2` key="text"**
**c = > json.get value=`turn2` key="llm_calls"**
**t = > json.get value=`turn2` key="tokens"**
1. not `c`
**c = 0**
2. *
**_ = 1**
1. not `t`
**t = 0**
2. *
**_ = 1**
**llm_calls = llm_calls + c**
**tokens = tokens + t**
**out = table.put in=`out` at="denied_tool" value=`tool_name`**
@@ -2410,6 +2558,14 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
**reply = > json.get value=`turn2` key="text"**
**c = > json.get value=`turn2` key="llm_calls"**
**t = > json.get value=`turn2` key="tokens"**
1. not `c`
**c = 0**
2. *
**_ = 1**
1. not `t`
**t = 0**
2. *
**_ = 1**
**llm_calls = llm_calls + c**
**tokens = tokens + t**
**out = table.put in=`out` at="tool" value=`tool_name`**
@@ -2866,17 +3022,28 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
> plan_echo_decompose workbook=`path` stream=`stream` echo=`echo`
**last_obs = > inspect_workbook path=`path`**
**turn = > plan_llm_act_loop agent=`self` goal=`goal` path=`path` observation=`last_obs` phase="decompose" explore_attempt=`explore_attempt` explore_n=`explore_n` stream=`stream` echo=`echo` events=`events`**
**dec = > json.get value=`turn` key="decision"**
**last_reply = > json.get value=`turn` key="reply"**
**last_obs = > json.get value=`turn` key="observation"**
**events = > json.get value=`turn` key="events"**
**turn_s = > json.stringify value=`turn`**
**turn_map = > text.starts_with text=`turn_s` prefix="{"**
**dec = None**
**last_reply = None**
1. `turn_map`
**dec = > json.get value=`turn` key="decision"**
**last_reply = > json.get value=`turn` key="reply"**
**last_obs = > json.get value=`turn` key="observation"**
**events = > json.get value=`turn` key="events"**
2. *
**dec = "TRANSPORT_ERROR"**
**last_reply = "plan_llm_act_loop_not_map"**
**err = `last_reply`**
1. `dec` == "TRANSPORT_ERROR"
**done = 1**
**status = "error"**
**err = > json.get value=`turn` key="error"**
1. not `err`
**err = `last_reply`**
**err = `last_reply`**
1. `turn_map`
**e2 = > json.get value=`turn` key="error"**
1. `e2`
**err = `e2`**
**summary = "llm transport error"**
**skip_loop = 1**
2. `dec` == CONTINUE
+61 -9
View File
@@ -23,16 +23,27 @@ Load `.env` from cwd (optional `path=`). Does not override existing variables.
## collect
+ `events`
Collapse a stream event list to final answer text (`done.result` or `error.message`). Prefer this over raw SSE fields. Alias: `stream_result`.
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 = ""**
- [ev](遍历 events 为 ev)
**t = > json.get value=`ev` key="type"**
1. `t` == "done"
**answer = > json.get value=`ev` key="result"**
**done_r = > json.get value=`ev` key="result"**
1. `done_r`
**answer = `done_r`**
2. *
**_ = 1**
2. `t` == "error"
**answer = > json.get value=`ev` key="message"**
**em = > json.get value=`ev` key="message"**
1. `em`
**answer = `em`**
2. *
**_ = 1**
3. `t` == "delta"
4. `t` == "text"
**chunk = > json.get value=`ev` key="text"**
@@ -40,9 +51,45 @@ Collapse a stream event list to final answer text (`done.result` or `error.messa
**answer = answer + chunk**
2. *
**_ = 1**
5. *
5. `t` == "data"
**raw = > json.get value=`ev` key="data"**
1. `raw`
1. `raw` == "[DONE]"
**_ = 1**
2. *
**parsed = > json.parse text=`raw`**
1. `parsed`
**choices = > json.get value=`parsed` key="choices"**
1. `choices`
**c0 = [1](access(choices, "1"))**
**delta = > json.get value=`c0` key="delta"**
1. `delta`
**piece = > json.get value=`delta` key="content"**
1. `piece`
**answer = answer + piece**
2. *
**_ = 1**
2. *
**msg = > json.get value=`c0` key="message"**
1. `msg`
**piece = > json.get value=`msg` key="content"**
1. `piece`
**answer = answer + piece**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
6. *
**_ = 1**
1. not `answer`
**answer = ""**
*answer*
## stream_result
@@ -347,8 +394,10 @@ inside the table is unsafe.
+ `prompt`=None
+ `path`=None
+ `echo`=False
+ `stream_kind`="delta"
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`**
@@ -361,7 +410,7 @@ Semantic stream: return the event list (use `llm.collect` to reduce to text). Om
2. *
**p = > prompt_body src=`raw`**
*> self.complete prompt=`p` stream=True echo=`echo`*
*> self.complete prompt=`p` stream=True echo=`echo` stream_kind=`stream_kind`*
## complete_result
+ `prompt`=None
@@ -370,24 +419,26 @@ Semantic stream: return the event list (use `llm.collect` to reduce to text). Om
+ `strict_selection`=False
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
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` suffix=[suffix](access(self, "suffix")) bearer=[bearer](access(self, "bearer"))*
*> 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"
Internal / compatibility primitive. Prefer `ask` / `stream` in new code.
1. `stream`
**pack = > self.complete_result prompt=`prompt` stream=True echo=`echo`**
**pack = > self.complete_result prompt=`prompt` stream=True echo=`echo` stream_kind=`stream_kind`**
**_ret = > json.get value=`pack` key="events"**
*_ret*
2. *
**pack = > self.complete_result prompt=`prompt` stream=False echo=`echo`**
**pack = > self.complete_result prompt=`prompt` stream=False echo=`echo` stream_kind=`stream_kind`**
**_ret = > json.get value=`pack` key="text"**
*_ret*
@@ -395,7 +446,8 @@ Internal / compatibility primitive. Prefer `ask` / `stream` in new code.
+ `prompt`
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
Alias for `complete` (compat).
*> self.complete prompt=`prompt` stream=`stream` echo=`echo`*
*> self.complete prompt=`prompt` stream=`stream` echo=`echo` stream_kind=`stream_kind`*
+3 -1
View File
@@ -80,17 +80,19 @@ Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list).
+ `auth_mode`=None
+ `stream`=False
+ `echo`=False
+ `stream_kind`="delta"
+ `suffix`=/chat/completions
+ `bearer`="Bearer "
POST `/chat/completions` (or stream SSE). Prefers `plugins/llm` ABI (`llm_chat_completions`) when the native plugin is resolvable; otherwise `lib/net` HTTP/SSE. Non-stream → `{text,usage,finish,tool_calls}`; stream → `{events,finish}`. 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"**
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` suffix=`suffix` bearer=`bearer`*
*> 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**
+50 -3
View File
@@ -20,14 +20,25 @@ description: >-
## 收集
+ `事件`
Collapse stream events to text. Supports semantic `delta`/`done.result` and
native-plugin raw frames (`type=data` + OpenAI chunk JSON).
**answer = ""**
- [ev](遍历 事件 为 ev)
**t = [type](access(ev, "type"))**
1. `t` == "done"
**answer = [result](access(ev, "result"))**
**done_r = [result](access(ev, "result"))**
1. `done_r`
**answer = `done_r`**
2. *
**_ = 1**
2. `t` == "error"
**answer = [message](access(ev, "message"))**
**em = [message](access(ev, "message"))**
1. `em`
**answer = `em`**
2. *
**_ = 1**
3. `t` == "delta"
4. `t` == "text"
**chunk = [text](access(ev, "text"))**
@@ -35,9 +46,45 @@ description: >-
**answer = answer + chunk**
2. *
**_ = 1**
5. *
5. `t` == "data"
**raw = [data](access(ev, "data"))**
1. `raw`
1. `raw` == "[DONE]"
**_ = 1**
2. *
**parsed = > json.parse text=`raw`**
1. `parsed`
**choices = [choices](access(parsed, "choices"))**
1. `choices`
**c0 = [1](access(choices, "1"))**
**delta = [delta](access(c0, "delta"))**
1. `delta`
**piece = [content](access(delta, "content"))**
1. `piece`
**answer = answer + piece**
2. *
**_ = 1**
2. *
**msg = [message](access(c0, "message"))**
1. `msg`
**piece = [content](access(msg, "content"))**
1. `piece`
**answer = answer + piece**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
2. *
**_ = 1**
6. *
**_ = 1**
1. not `answer`
**answer = ""**
*answer*
## 流式结果
+104 -4
View File
@@ -98,22 +98,88 @@ fn cancel_requested() -> bool {
{
return true;
}
// Web sse-live creates an empty token file up front; only an explicit
// body ("1" / "cancelled") means the client asked to stop. Empty ≠ cancel.
if let Ok(tok) = std::env::var("MARQDO_CANCEL_TOKEN") {
let path = std::path::Path::new(&tok);
if path.is_file() {
if let Ok(body) = std::fs::read_to_string(path) {
let t = body.trim();
return t.is_empty() || t == "1" || t.eq_ignore_ascii_case("cancelled");
return t == "1" || t.eq_ignore_ascii_case("cancelled");
}
return true;
}
}
false
}
fn parse_sse_events(reader: impl BufRead, echo: bool) -> Result<Vec<Value>, String> {
/// Mirror host `net::push_openai_delta_events`: append semantic frames to
/// `MARQDO_EVENT_FORWARD` so subtask/web sse-live can flush tokens before the
/// lib call returns (OpenAI-style incremental SSE).
fn forward_event_bus_frame(ev: &Value) {
let Ok(path) = std::env::var("MARQDO_EVENT_FORWARD") else {
return;
};
if path.is_empty() {
return;
}
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let _ = writeln!(f, "{ev}");
let _ = f.flush();
}
}
/// Publish `{type:delta|plan|reasoning|error, text|message}` from one OpenAI chunk.
/// `content_type` is usually `delta` (answer tokens) or `plan` (parent protocol LLM).
fn forward_openai_chunk(data: &str, content_type: &str) {
let data = data.trim();
if data.is_empty() || data == "[DONE]" {
return;
}
let Ok(v) = serde_json::from_str::<Value>(data) else {
return;
};
if let Some(msg) = v.get("error").and_then(|e| {
e.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
}) {
forward_event_bus_frame(&json!({"type": "error", "message": msg}));
return;
}
let reasoning = v
.pointer("/choices/0/delta/reasoning_content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !reasoning.is_empty() {
forward_event_bus_frame(&json!({"type": "reasoning", "text": reasoning}));
}
let content = v
.pointer("/choices/0/delta/content")
.and_then(|c| c.as_str())
.unwrap_or("");
if !content.is_empty() {
let ty = if content_type.is_empty() {
"delta"
} else {
content_type
};
forward_event_bus_frame(&json!({"type": ty, "text": content}));
}
}
fn parse_sse_events(
reader: impl BufRead,
echo: bool,
content_type: &str,
) -> Result<Vec<Value>, String> {
let mut events = Vec::new();
let mut data_lines: Vec<String> = Vec::new();
let mut accumulated = String::new();
for line in reader.lines() {
if cancel_requested() {
events.push(json!({"type": "cancelled", "message": "MARQDO_CANCEL"}));
@@ -128,9 +194,23 @@ fn parse_sse_events(reader: impl BufRead, echo: bool) -> Result<Vec<Value>, Stri
let data = data_lines.join("\n");
data_lines.clear();
if data.trim() == "[DONE]" {
// Parent owns run lifecycle `done`; only forward for answer streams.
if content_type == "delta" || content_type.is_empty() {
let done = json!({"type": "done", "result": accumulated});
forward_event_bus_frame(&done);
}
events.push(json!({"type": "done", "data": "[DONE]"}));
break;
}
forward_openai_chunk(&data, content_type);
if let Ok(v) = serde_json::from_str::<Value>(&data) {
if let Some(c) = v
.pointer("/choices/0/delta/content")
.and_then(|x| x.as_str())
{
accumulated.push_str(c);
}
}
events.push(json!({"type": "data", "data": data}));
}
continue;
@@ -142,8 +222,13 @@ fn parse_sse_events(reader: impl BufRead, echo: bool) -> Result<Vec<Value>, Stri
if !data_lines.is_empty() {
let data = data_lines.join("\n");
if data.trim() == "[DONE]" {
if content_type == "delta" || content_type.is_empty() {
let done = json!({"type": "done", "result": accumulated});
forward_event_bus_frame(&done);
}
events.push(json!({"type": "done", "data": "[DONE]"}));
} else {
forward_openai_chunk(&data, content_type);
events.push(json!({"type": "data", "data": data}));
}
}
@@ -252,6 +337,8 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
let messages = build_messages(args)?;
let stream = opt_bool(args, "stream", false);
let echo = opt_bool(args, "echo", false);
// Answer tokens → "delta"; parent plan protocol → "plan" (UI process trail).
let stream_kind = opt_text(args, "stream_kind").unwrap_or("delta");
let suffix = opt_text(args, "suffix").unwrap_or("/chat/completions");
let bearer = opt_text(args, "bearer").unwrap_or("Bearer ");
@@ -309,7 +396,8 @@ fn chat_completions(args: &Value) -> Result<Value, String> {
"transport": "plugin",
}));
}
let events = parse_sse_events(BufReader::new(r.into_reader()), echo)?;
let events =
parse_sse_events(BufReader::new(r.into_reader()), echo, stream_kind)?;
Ok(json!({
"events": events,
"finish": "stop",
@@ -525,6 +613,18 @@ mod tests {
assert_eq!(out["finish"], "cancelled");
}
#[test]
fn f06_empty_cancel_token_is_not_cancelled() {
// sse-live creates an empty token file; that must NOT abort the turn.
let tok = std::env::temp_dir().join(format!("llm-cancel-empty-{}", std::process::id()));
std::fs::write(&tok, "").unwrap();
std::env::set_var("MARQDO_CANCEL_TOKEN", &tok);
std::env::remove_var("MARQDO_CANCEL");
assert!(!cancel_requested());
std::env::remove_var("MARQDO_CANCEL_TOKEN");
let _ = std::fs::remove_file(&tok);
}
/// F01: two local endpoints receive distinct models/auth — no cross-talk.
#[test]
fn f01_dual_endpoint_isolation() {
+15
View File
@@ -799,6 +799,13 @@ func (g *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking")
}
func (g *gzipResponseWriter) Flush() {
_ = g.w.Flush()
if f, ok := g.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
type statusRecorder struct {
http.ResponseWriter
status int
@@ -816,6 +823,14 @@ func (s *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking")
}
// Flush must be forwarded so sse-live / EventBus token streams are not buffered
// behind access-log wrapping (otherwise clients see 0 bytes until the invoke ends).
func (s *statusRecorder) Flush() {
if f, ok := s.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
+18 -2
View File
@@ -137,6 +137,11 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo
if err != nil {
code := http.StatusInternalServerError
msg := err.Error()
if strings.Contains(msg, "interpreter busy") {
w.Header().Set("Retry-After", "2")
jsonErr(w, http.StatusServiceUnavailable, msg)
return
}
if strings.Contains(msg, "unknown library") ||
strings.Contains(msg, "call_lib_path: need") ||
strings.Contains(msg, "not allowed") ||
@@ -260,6 +265,10 @@ func (st *state) handleInvokeLiveSSE(w http.ResponseWriter, r *http.Request, rou
done := make(chan callResult, 1)
go func() {
v, e := plugin.CallLibPath(route.FnPath, args)
if e != nil && strings.Contains(e.Error(), "interpreter busy") {
// Another invoke still holds the lock — surface as failed run, not hang.
e = fmt.Errorf("interpreter busy: try again shortly")
}
done <- callResult{value: v, err: e}
}()
@@ -339,13 +348,20 @@ func normalizeLiveSSELine(seq uint64, line string) map[string]any {
base["seq"] = seq
return base
}
// LLM plugin / net SSE: {type:delta|reasoning, text:...}
if t, _ := obj["type"].(string); t == "delta" || t == "reasoning" {
// LLM plugin / net SSE: {type:delta|plan|reasoning, text:...}
if t, _ := obj["type"].(string); t == "delta" || t == "plan" || t == "reasoning" {
text, _ := obj["text"].(string)
base["type"] = "message.delta"
base["payload"] = map[string]any{"delta": text, "kind": t}
return base
}
// Plan process cards — keep as message.delta for back-compat, but never
// promote `result` into payload.delta (that caused full-answer duplication).
if t, _ := obj["type"].(string); t == "decompose" || t == "decision" || t == "await" || t == "round" || t == "done" || t == "tool_start" || t == "tool_end" || t == "plan_act" {
base["type"] = "message.delta"
base["payload"] = obj
return base
}
if text, ok := obj["text"].(string); ok && text != "" {
base["type"] = "message.delta"
base["payload"] = map[string]any{"delta": text}
+5 -2
View File
@@ -326,8 +326,11 @@ pub fn apply_patch_blocks(
};
match apply_patch_blocks_inner(ctx, path, text) {
Ok(n) => Ok(n),
// soft only swallows unique-FIND miss — never parse / multi-match / whole-file.
Err(e) if soft && e.contains("FIND not found") => Ok(Value::Int(0)),
// soft swallows unique-FIND miss and empty FIND (model protocol mistakes).
// Never softens parse / multi-match / whole-file rewrite.
Err(e) if soft && (e.contains("FIND not found") || e.contains("empty FIND")) => {
Ok(Value::Int(0))
}
Err(e) => Err(e),
}
}
+46 -2
View File
@@ -6,7 +6,8 @@ use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
use libloading::{Library, Symbol};
@@ -75,6 +76,8 @@ static GLOBAL_HOST: OnceLock<Mutex<SendPtr<HostContext>>> = OnceLock::new();
/// Process-wide lib-path hook (same lifetime as GLOBAL_HOST).
static GLOBAL_LIB_PATH: OnceLock<Mutex<SendLibPath>> = OnceLock::new();
/// Serialize interpreter re-entry from HTTP worker threads.
/// HostContext is not Sync — one Marqdo invoke at a time. Short routes must
/// fail fast (`interpreter busy`) so a long SSE chat cannot freeze the UI.
static INVOKE_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
fn global_host_slot() -> &'static Mutex<SendPtr<HostContext>> {
@@ -89,6 +92,41 @@ fn invoke_lock() -> &'static Mutex<()> {
INVOKE_LOCK.get_or_init(|| Mutex::new(()))
}
/// Default wait for short HTTP invokes (`MARQDO_INVOKE_WAIT_MS`, default 1500ms).
/// Do not raise this process-wide during SSE — concurrent short routes would hang again.
/// See doc/adr/0008-web-invoke-serialization.md.
fn invoke_wait_budget() -> Duration {
const DEFAULT_MS: u64 = 1500;
match std::env::var("MARQDO_INVOKE_WAIT_MS") {
Ok(s) => {
let ms = s.trim().parse::<u64>().unwrap_or(DEFAULT_MS);
Duration::from_millis(ms.max(1))
}
Err(_) => Duration::from_millis(DEFAULT_MS),
}
}
fn acquire_invoke_lock() -> Result<MutexGuard<'static, ()>, String> {
let budget = invoke_wait_budget();
let deadline = Instant::now() + budget;
let lock = invoke_lock();
loop {
match lock.try_lock() {
Ok(g) => return Ok(g),
Err(std::sync::TryLockError::Poisoned(p)) => return Ok(p.into_inner()),
Err(std::sync::TryLockError::WouldBlock) => {
if Instant::now() >= deadline {
return Err(format!(
"interpreter busy: another request holds the Marqdo invoke lock (waited {}ms)",
budget.as_millis()
));
}
std::thread::sleep(Duration::from_millis(15));
}
}
}
}
/// Hook: resolve bare `lib.member` (and longer paths) in the site module's import tree.
#[derive(Clone, Copy)]
pub struct LibPathCall {
@@ -300,7 +338,13 @@ unsafe extern "C" fn host_query(
let _invoke_guard;
let from_worker = CURRENT_HOST.with(|c| c.get().is_null());
if from_worker {
_invoke_guard = invoke_lock().lock().unwrap_or_else(|e| e.into_inner());
match acquire_invoke_lock() {
Ok(g) => _invoke_guard = g,
Err(msg) => {
set_err(&msg);
return 1;
}
}
}
let ctx = &mut *ctx_ptr;