From dbb276555363749c04010d5b7667fb27e9f6620b Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 11 Aug 2026 09:11:15 +0800 Subject: [PATCH] Add parent Plan-and-Move: CALL/READ tools and quiet I/O capture. Give the plan loop actionable observation (source excerpts, stderr/stdout tails) and short stop rules so the parent can inspect children and use stdlib helpers instead of inventing long patches. Co-authored-by: Cursor --- doc/design/ext-agent-parent.md | 141 ++++++ doc/design/ext-agent-plan.md | 18 +- doc/design/ext-agent.md | 2 +- doc/design/stdlib-subtask.md | 4 +- doc/roadmap/agent-streaming.md | 2 +- ext/ai/agent.mq.md | 691 +++++++++++++++++++++++----- lib/subtask.mq.md | 6 +- lib/子任务.mq.md | 5 +- src/host/subtask.rs | 81 +++- tests/ext/agent-plan-decision.mq.md | 27 ++ tests/ext/agent-plan-observe.mq.md | 37 ++ tests/gold.rs | 15 +- tests/lib/subtask-child-print.mq.md | 9 + tests/lib/subtask-quiet-io.mq.md | 24 + 14 files changed, 932 insertions(+), 130 deletions(-) create mode 100644 doc/design/ext-agent-parent.md create mode 100644 tests/ext/agent-plan-observe.mq.md create mode 100644 tests/lib/subtask-child-print.mq.md create mode 100644 tests/lib/subtask-quiet-io.mq.md diff --git a/doc/design/ext-agent-parent.md b/doc/design/ext-agent-parent.md new file mode 100644 index 0000000..e5cdb5f --- /dev/null +++ b/doc/design/ext-agent-parent.md @@ -0,0 +1,141 @@ +# 父智能体 Plan-and-Move(`## plan` 行动面) + +| | | +|---|---| +| 状态 | **Accepted** | +| 日期 | 2026-08-11 | +| 父文档 | [ext-agent-plan.md](ext-agent-plan.md) · [ext-agent.md](ext-agent.md) | +| 相关 | [stdlib-subtask.md](stdlib-subtask.md) · [okf.md](okf.md) · [ai-skill.md](ai-skill.md) | + +--- + +## 1. 一句话 + +**父智能体 = Plan-and-Move 控制器**:观察工作簿与子任务结果 → 规划下一步 → 行动(读 / 调工具 / 补丁 / 再跑 / 停);Marqdo「文档即代码」让工具、记忆与程序都落在 `.mq.md` 上。 + +--- + +## 2. 为何需要强化 + +单靠 `DECISION: DONE|CONTINUE|RUN` 时,父侧几乎没有「手」: + +| 缺口 | 后果 | +|------|------| +| 看不到子源码 / 报错 / stdout | 空想 FIND/REPLACE,输出又臭又长 | +| 标准库未进入行动表 | 无法在规划环内用 `fs` / `json` / `subtask` 等 | +| 不能用 Marqdo 造工具 | 无法把可复用步骤沉淀为 `##` | +| 提示词过长且互相打架 | 模型「继续帮忙」而不停机 | + +业界对 agent 回环的共识:成功标准、停机动作、**确定性行动面**三者必须写清;停机最终靠代码护栏,不只靠 prompt。 + +--- + +## 3. Marqdo 赋予的特性(相对通用 Plan-and-Move) + +| 特性 | 含义 | +|------|------| +| 工作簿即程序 | 子执行物是可 `spawn path=` 的 `.mq.md`,不是隐式任务图 | +| 固化即记忆 | `DECISION: DONE` → `agent_workbook_solidify` + OKF 晋升 | +| `lib/*` 即工具 | 标准库是父可调度能力;经父 helper 或写入工作簿/`tools/` 后调用 | +| 补丁即改代码 | `CONTINUE` + 精确 FIND/REPLACE;禁止整文件 LLM 重写 | +| 文档即提示 | 站立提示、Skill 摘要、观察切片都是可读 Markdown,而非黑盒 system blob | + +--- + +## 4. 循环形状(锁定) + +```text + ┌──────────────┐ + │ Plan (LLM) │ + └──────┬───────┘ + │ 协议回复 + ┌─────────────┼─────────────┐ + ▼ ▼ ▼ + READ:/CALL: DECISION: (无效 → error) + │ DONE/RUN/ + │ CONTINUE + ▼ ▼ + Act 工具 Move(固化/补丁/spawn) + │ │ + └──────┬──────┘ + ▼ + Observe(有界) + │ + └──► 回到 Plan 或终止 +``` + +优先级(解析父回复时): + +1. **`CALL:` / `调用:`** — 跑父侧工具,结果并入 observation,再 Plan +2. **`READ:` / `读取:`** — 加深某一观察切片,再 Plan +3. **`DECISION:`** — Move(含运行时 solidify / apply_patch / spawn) + +--- + +## 5. 观察面(有界、可加深) + +`inspect_workbook` / `await_workbook` 在磁盘上可持有全文;**注入父 prompt 的默认紧凑观察**必须可行动且短: + +| 字段 | 默认 | `READ:` 加深 | +|------|------|----------------| +| `source_excerpt` | 去 `` 后的结构摘录,硬顶 ~4KiB / ~80 行 | `READ:source` → 更大但仍有硬顶的摘录 | +| `stderr_tail` / `stdout_tail` | 子任务捕获尾部 ~2KiB | `READ:stderr` / `READ:stdout` | +| `value` | ≤200 字;否则 `value_preview` + `value_len` | (一般不必加深) | +| `slots` | `{key,line,body_len}`;`error` 槽可带短预览 | `READ:slots` | +| `has_worker_step` / `solidify_on_done` | 布尔提示 | — | + +`quiet=True` **只表示不污染父 TTY**;file `wait` 仍返回截断后的 `stdout` / `stderr` 供父观察。 + +--- + +## 6. 工具面 + +### 6.1 父侧内建 helper(`CALL:` 首批) + +写在 `ext/ai/agent.mq.md`,由 plan 循环直接调度(**不用** OpenAI function calling): + +| 名称 | 作用 | +|------|------| +| `workbook_read` | 按 depth 读工作簿摘录 | +| `workbook_excerpt` | 结构摘录(默认观察同源) | +| `lib_catalog` | 枚举 `lib/*.mq.md` 能力摘要 | +| `scratch_tool_write` | 写入 `.marqdo/agent-runs/tools/.mq.md` | + +### 6.2 标准库与造工具 + +- **标准库**:父通过 `lib_catalog` 知晓能力;把 `> lib/….mq.md` 与 `##` 写进工作簿(PATCH)或 scratch 工具文件后即可被子任务 / 后续 `CALL` 使用。 +- **造工具**:优先 `CONTINUE` + 短 PATCH 在工作簿内新增 `##`;或 `CALL:scratch_tool_write` 沉淀独立工具文件。 +- **非目标(本阶段)**:把全部 `lib/*` 自动反射成 JSON tools schema;原生 function calling。 + +--- + +## 7. 输出纪律(停机规则) + +父回复**只允许**协议行 + 一行 `SUMMARY` + 短 PATCH(`<20` 行)。禁止长独白 / 行程散文 / 把 observation 粘进 REPLACE。 + +修订阶段硬规则(自上而下): + +1. `exit_code==0` 且 `has_value` → **立刻** `DECISION: DONE`(运行时 solidify);`has_worker_step` **不是** CONTINUE 的理由。 +2. 仅失败 / 无值 / 明确未达目标时才 `CONTINUE`。 +3. 代码护栏:非 `improve` 时,子已返回值则 **跳过父 LLM**,直接 solidify + DONE。 + +--- + +## 8. 与 `## step` 的关系 + +| | `step`(子) | `plan`(父) | +|---|-------------|-------------| +| 协议 | `CALL:` 或最终答案 | `CALL:` / `READ:` / `DECISION:` | +| 工具来源 | 工作簿 / 调用方 allowlist | 父 helper + 写入的 Marqdo `##` | +| 成功出口 | 返回答案文本 | `DONE` + solidify / promote | + +--- + +## 9. 实现落点 + +| 组件 | 路径 | +|------|------| +| 设计(本文) | `doc/design/ext-agent-parent.md` | +| 多步总设计增量 | `doc/design/ext-agent-plan.md` §4.1 / 协议 | +| 子任务 I/O | `src/host/subtask.rs`、`lib/subtask.mq.md` | +| 父循环 / 观察 / 提示 | `ext/ai/agent.mq.md` | diff --git a/doc/design/ext-agent-plan.md b/doc/design/ext-agent-plan.md index b410036..2699243 100644 --- a/doc/design/ext-agent-plan.md +++ b/doc/design/ext-agent-plan.md @@ -5,7 +5,7 @@ | 状态 | **Accepted;D2a 已落地;D2b–D2d(观察→补丁式多步)实现中** | | 日期 | 2026-08-07 | | 父文档 | [ext-agent.md](ext-agent.md) | -| 相关 | [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [module-namespace.md](module-namespace.md) · [ai-skill.md](ai-skill.md) · [objects.md](objects.md) | +| 相关 | [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move 行动面**) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [module-namespace.md](module-namespace.md) · [ai-skill.md](ai-skill.md) · [objects.md](objects.md) | --- @@ -82,22 +82,28 @@ ## 4.1 观察面与补丁(锁定) -父每次二次规划前必须拿到观察 map(`inspect_workbook`): +父每次二次规划前必须拿到观察 map(`inspect_workbook` / `await_workbook`)。磁盘可持全文;**注入父 LLM 的默认观察为有界紧凑面**(摘录 + I/O 尾部)。完整语义与 `READ:` / `CALL:` 行动面见 [ext-agent-parent.md](ext-agent-parent.md)。 | 字段 | 含义 | |------|------| | `path` | 工作簿路径 | -| `source` | 最新全文 | +| `source` | 最新全文(磁盘);prompt 默认用 `source_excerpt` | | `exit_code` | 上一轮子任务退出码 | | `value` | 子 `# main` 返回值(经 `await_workbook` / `wait.value`) | +| `stdout` / `stderr` | 子任务捕获(`quiet` 仅静音 TTY,不丢弃数据) | | `slots` | 命名写回列表(`key` + `body`) | | `last_ok` / `last_error` | 便捷字段 | -二次规划输出协议(机器可解析;**禁止**只输出整份 `.mq.md`): +二次规划输出协议(机器可解析;**禁止**只输出整份 `.mq.md`;**禁止**长独白): ```text +CALL: +READ:source|stderr|stdout|slots + DECISION: DONE -SUMMARY: <汇总> +SUMMARY: <一行> + +DECISION: RUN DECISION: CONTINUE PATCH: @@ -110,7 +116,7 @@ REPLACE >>> ``` -应用器对文件做**精确** FIND→REPLACE;找不到则报错,由父缩小补丁。优先把已验证的 `step` **固化为返回答案的普通代码**(`**…**`,不要只靠 `print`)。 +解析优先级:`CALL` → `READ` → `DECISION`。应用器对文件做**精确** FIND→REPLACE;找不到则报错。`DONE` 时运行时 `agent_workbook_solidify` 固化答案(不必靠长 REPLACE 粘贴子散文)。 --- diff --git a/doc/design/ext-agent.md b/doc/design/ext-agent.md index 14e37b0..5ed62af 100644 --- a/doc/design/ext-agent.md +++ b/doc/design/ext-agent.md @@ -4,7 +4,7 @@ |---|---| | Status | **Accepted · redesign**(取代「thin TOOL: loop」方案) | | Date | 2026-08-07 | -| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) | +| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) | ## 0. 为什么要改掉旧方案 diff --git a/doc/design/stdlib-subtask.md b/doc/design/stdlib-subtask.md index fdd9fa8..e24a268 100644 --- a/doc/design/stdlib-subtask.md +++ b/doc/design/stdlib-subtask.md @@ -11,14 +11,14 @@ | 参数 | 执行方式 | `join` / `wait` 返回值 | |------|----------|------------------------| -| `path=` | `marqdo run --emit-result ` 子进程 | map `{ code: Int, value: Value\|null }`(`# main` 返回值;与 `quiet` 无关) | +| `path=` | `marqdo run --emit-result ` 子进程 | map `{ code, value, stdout?, stderr? }`(`# main` 返回值;quiet 时 piped 捕获 I/O 尾部,不 inherit TTY) | | `fn=` + 可选 `args=` | 当前入口模块中的函数(进程内线程) | 函数返回值 `Value` | | `code=` | 外联代码块(`Value::Code`)子进程 | stdout `Text` | | `lang=` + `source=` | 外联源码子进程 | stdout `Text` | `args=`:文件子任务为 `List`(命令行参数);函数子任务为 `Map`(形参绑定)或 `List`(按 `arg0`… 命名)。 -`quiet=` / `静默=`(默认 `True`):仅影响 **文件** 子任务的 **TTY**。默认接到 null(父终端不被子 `print` 污染);`False` 时继承父进程 stdout/stderr。**答案载荷走 `# main` 的返回值**(经 `--emit-result` 旁路),不依赖 print。外联子任务仍经管道收集 stdout 供 `join` 返回,不受此参数影响。 +`quiet=` / `静默=`(默认 `True`):仅影响 **文件** 子任务的 **TTY**。默认 **piped 捕获** stdout/stderr(父终端不被污染,`wait` map 带截断后的 `stdout`/`stderr` 供父智能体观察);`False` 时继承父进程 stdout/stderr(map 中 I/O 字段为空)。**答案载荷仍以 `# main` 返回值为主**(经 `--emit-result` 旁路)。外联子任务仍经管道收集 stdout 供 `join` 返回,不受此参数影响。 父进程结束(含 panic)时 **KillOnDrop** 终止所有文件/外联子进程;函数线程标记为 killed 并 detach(无法强杀 OS 线程)。 diff --git a/doc/roadmap/agent-streaming.md b/doc/roadmap/agent-streaming.md index bcf4c46..8d76765 100644 --- a/doc/roadmap/agent-streaming.md +++ b/doc/roadmap/agent-streaming.md @@ -4,7 +4,7 @@ |---|---| | 状态 | **S0–S3 已落地**(view SSE) | | 日期 | 2026-08-10 | -| 相关 | [ext-llm.md](../design/ext-llm.md) · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [view.md](../design/view.md) | +| 相关 | [ext-llm.md](../design/ext-llm.md) · [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md)(父 Plan-and-Move / CALL·READ) · [stdlib-subtask.md](../design/stdlib-subtask.md) · [view.md](../design/view.md) | | 痛点 | `complete` / `step` / `plan` 均为整段返回;用户看不到思考与中间输出 | --- diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index 422ac16..47f5d02 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -135,8 +135,10 @@ Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skel + `path` + `exit_code`=None + `value`=None + + `stdout`=None + + `stderr`=None -Structured observation for the parent developer-agent: source, named writeback slots, exit code, and optional child return value. +Structured observation for the parent developer-agent: source, named writeback slots, exit code, optional child return value, and quiet-captured I/O. *`source` = > fs.read_text path=`path` * *`slots` = > writeback.scan_path path=`path` * @@ -149,6 +151,14 @@ Structured observation for the parent developer-agent: source, named writeback s *`obs` = > json.set map=`obs` key=value value=`value` * 2. * *`_` = 1* +1. `stdout` + *`obs` = > json.set map=`obs` key=stdout value=`stdout` * +2. * + *`_` = 1* +1. `stderr` + *`obs` = > json.set map=`obs` key=stderr value=`stderr` * +2. * + *`_` = 1* *`last_ok` = None* *`last_error` = None* @@ -179,13 +189,15 @@ Structured observation for the parent developer-agent: source, named writeback s ## await_workbook + `path` -Spawn a workbook file (quiet by default), wait for `{code,value}`, and inspect. Parent consumes `value` — not child stdout. +Spawn a workbook file (quiet by default), wait for `{code,value,stdout?,stderr?}`, and inspect. *`id` = > subtask.spawn path=`path` * *`waited` = > subtask.wait id=`id` * *`code` = > json.get value=`waited` key=code * *`value` = > json.get value=`waited` key=value * -*`obs` = > inspect_workbook path=`path` exit_code=`code` value=`value` * +*`stdout` = > json.get value=`waited` key=stdout * +*`stderr` = > json.get value=`waited` key=stderr * +*`obs` = > inspect_workbook path=`path` exit_code=`code` value=`value` stdout=`stdout` stderr=`stderr` * *`out` = > json.parse text={"code":0} * *`out` = > json.set map=`out` key=code value=`code` * *`out` = > json.set map=`out` key=value value=`value` * @@ -194,6 +206,492 @@ Spawn a workbook file (quiet by default), wait for `{code,value}`, and inspect. --- +## text_head_lines + + `text` + + `max_lines`=80 + + `max_chars`=4000 + +*`esc` = > json.parse text={"nl":"\n"} * +*`nl` = > json.get value=`esc` key=nl * +*`raw` = > str value=`text` * +*`lines` = > split value=`raw` sep=`nl` * +*`acc` = > json.parse text=[] * +*`chars` = 0* +*`count` = 0* +- [`line`](`lines`) + 1. `count` < `max_lines` + *`ln` = > len value=`line` * + *`next` = `chars` + `ln` * + 1. `next` > `max_chars` + *`count` = `max_lines`* + 2. * + *`acc` = > json.append list=`acc` item=`line` * + *`chars` = `next`* + *`count` = `count` + 1* + 2. * + *`_` = 1* +**> join value=`acc` sep=`nl`** + +--- + +## text_tail_lines + + `text` + + `max_lines`=40 + + `max_chars`=2000 + +*`esc` = > json.parse text={"nl":"\n"} * +*`nl` = > json.get value=`esc` key=nl * +*`raw` = > str value=`text` * +*`lines` = > split value=`raw` sep=`nl` * +*`n` = > len value=`lines` * +*`start` = `n` - `max_lines` * +1. `start` < 0 + *`start` = 0* +2. * + *`_` = 1* +*`acc` = > json.parse text=[] * +*`i` = 0* +*`chars` = 0* +- [`line`](`lines`) + 1. `i` >= `start` + *`ln` = > len value=`line` * + *`next` = `chars` + `ln` * + 1. `next` > `max_chars` + *`i` = `n`* + 2. * + *`acc` = > json.append list=`acc` item=`line` * + *`chars` = `next`* + 2. * + *`_` = 1* + *`i` = `i` + 1* +**> join value=`acc` sep=`nl`** + +--- + +## strip_html_comments + + `text` + +Drop `` blocks (including marqdo-out bodies) so parent excerpts stay structural. + +*`esc` = > json.parse text={"nl":"\n"} * +*`nl` = > json.get value=`esc` key=nl * +*`raw` = > str value=`text` * +*`lines` = > split value=`raw` sep=`nl` * +*`acc` = > json.parse text=[] * +*`skip` = None* +- [`line`](`lines`) + 1. `skip` + *`end_parts` = > split value=`line` sep=--> * + *`en` = > len value=`end_parts` * + 1. `en` > 1 + *`skip` = None* + 2. * + *`_` = 1* + 2. * + *`start_parts` = > split value=`line` sep= * + *`en` = > len value=`end_parts` * + 1. `en` > 1 + *`skip` = None* + 2. * + *`skip` = 1* + 2. * + *`acc` = > json.append list=`acc` item=`line` * +**> join value=`acc` sep=`nl`** + +--- + +## workbook_source_excerpt + + `source` + + `max_lines`=80 + + `max_chars`=4000 + +*`clean` = > strip_html_comments text=`source` * +**> text_head_lines text=`clean` max_lines=`max_lines` max_chars=`max_chars`** + +--- + +## workbook_excerpt + + `path` + + `max_lines`=80 + + `max_chars`=4000 + +*`src` = > fs.read_text path=`path` * +**> workbook_source_excerpt source=`src` max_lines=`max_lines` max_chars=`max_chars`** + +--- + +## workbook_read + + `path` + + `depth`=default + +*`src` = > fs.read_text path=`path` * +1. `depth` == deep + **> workbook_source_excerpt source=`src` max_lines=200 max_chars=12000** +2. * + **> workbook_source_excerpt source=`src` max_lines=80 max_chars=4000** + +--- + +## lib_catalog + +Short catalog of English stdlib modules the parent may wire into workbooks or scratch tools. + +*`out` = > json.parse text={"note":"Import via frontmatter > lib/.mq.md then call ## members. Prefer PATCH workbook or CALL:scratch_tool_write over inventing prose.","files":["fs.mq.md","json.mq.md","subtask.mq.md","sys.mq.md","writeback.mq.md","text.mq.md","time.mq.md","math.mq.md","net.mq.md","table.mq.md","plugin.mq.md","foreign.mq.md"]} * +**`out`** + +--- + +## scratch_tool_write + + `name` + + `text` + +Write a scratch tool workbook under `.marqdo/agent-runs/tools/.mq.md`. + +*`esc` = > json.parse text={"a":".marqdo/agent-runs/tools/","b":".mq.md"} * +*`a` = > json.get value=`esc` key=a * +*`b` = > json.get value=`esc` key=b * +*`dir` = .marqdo/agent-runs/tools * +> fs.make_dir path=`dir` +*`path` = `a` + `name` + `b` * +> fs.write_text path=`path` text=`text` +*`out` = > json.parse text={"ok":True} * +*`out` = > json.set map=`out` key=path value=`path` * +**`out`** + +--- + +## skill_brief + + `max_chars`=1200 + +*`skill` = > agent_marqdo_skill * +**> text_head_lines text=`skill` max_lines=40 max_chars=`max_chars`** + +--- + +## extract_plan_read + + `reply` + +Parse READ:source|stderr|stdout|slots (Chinese: 读取:…). + +*`esc` = > json.parse text={"nl":"\n","fw":":"} * +*`nl` = > json.get value=`esc` key=nl * +*`fw` = > json.get value=`esc` key=fw * +*`text` = > trim value=`reply` * +*`lines` = > split value=`text` sep=`nl` * +*`found` = None* +- [`line`](`lines`) + *`t` = > trim value=`line` * + *`parts` = > split value=`t` sep=: * + *`n` = > 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` * + 1. `head` == READ + *`found` = `rest`* + 2. `head` == 读取 + *`found` = `rest`* + 3. * + *`_` = 1* + 2. * + *`parts` = > split value=`t` sep=`fw` * + *`n` = > 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` * + 1. `head` == 读取 + *`found` = `rest`* + 2. `head` == READ + *`found` = `rest`* + 3. * + *`_` = 1* + 2. * + *`_` = 1* +**`found`** + +--- + +## extract_plan_act + + `reply` + +Priority: CALL → READ → DECISION. Returns `{kind,name}`. + +*`tool` = > extract_tool_name reply=`reply` * +1. `tool` + *`out` = > json.parse text={"kind":"call"} * + *`out` = > json.set map=`out` key=name value=`tool` * + **`out`** +2. * + *`_` = 1* +*`rk` = > extract_plan_read reply=`reply` * +1. `rk` + *`out` = > json.parse text={"kind":"read"} * + *`out` = > json.set map=`out` key=name value=`rk` * + **`out`** +2. * + *`_` = 1* +*`dec` = > extract_plan_decision reply=`reply` * +1. `dec` + *`out` = > json.parse text={"kind":"decision"} * + *`out` = > json.set map=`out` key=name value=`dec` * + **`out`** +2. * + *`out` = > json.parse text={"kind":"unknown"} * + **`out`** + +--- + +## extract_scratch_tool + + `reply` + +Parse NAME: id plus a triple-angle body after CALL:scratch_tool_write. + +*`esc` = > json.parse text={"nl":"\n","open":"<<<","close":">>>"} * +*`nl` = > json.get value=`esc` key=nl * +*`open` = > json.get value=`esc` key=open * +*`close` = > json.get value=`esc` key=close * +*`text` = > trim value=`reply` * +*`lines` = > split value=`text` sep=`nl` * +*`name` = None* +*`body_lines` = > json.parse text=[] * +*`in_body` = None* +- [`line`](`lines`) + 1. `in_body` + *`t` = > trim value=`line` * + 1. `t` == `close` + *`in_body` = None* + 2. * + *`body_lines` = > json.append list=`body_lines` item=`line` * + 2. * + *`t` = > trim value=`line` * + *`parts` = > split value=`t` sep=: * + *`n` = > 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` * + 1. `head` == NAME + *`name` = `rest`* + 2. `head` == 名称 + *`name` = `rest`* + 3. * + *`_` = 1* + 2. * + *`_` = 1* + 1. `t` == `open` + *`in_body` = 1* + 2. * + *`_` = 1* +*`body` = > join value=`body_lines` sep=`nl` * +*`out` = > json.parse text={} * +*`out` = > json.set map=`out` key=name value=`name` * +*`out` = > json.set map=`out` key=text value=`body` * +**`out`** + +--- + +## run_parent_tool + + `name` + + `path` + + `observation`=None + + `reply`=None + +Parent Plan-and-Move tools (stdlib-aware helpers in this module). + +1. `name` == workbook_read + **> workbook_read path=`path` depth=deep** +2. `name` == workbook_excerpt + **> workbook_excerpt path=`path`** +3. `name` == lib_catalog + **> 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 * + *`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` + **> scratch_tool_write name=`tn` text=`tt`** + 2. * + **> json.get value=`errs` key=a** + 2. * + **> json.get value=`errs` key=b** +5. * + *`msg` = Parent tool not allowed: * + **`msg` + `name`** + +--- + +## plan_read_deepen + + `observation` + + `kind` + + `path` + +*`obs` = `observation` * +1. `kind` == source + *`ex` = > workbook_read path=`path` depth=deep * + *`obs` = > json.set map=`obs` key=source_excerpt value=`ex` * + *`obs` = > json.set map=`obs` key=read_source value=True * +2. `kind` == stderr + *`err` = > json.get value=`obs` key=stderr * + *`tail` = > text_tail_lines text=`err` max_lines=80 max_chars=6000 * + *`obs` = > json.set map=`obs` key=stderr_tail value=`tail` * + *`obs` = > json.set map=`obs` key=read_stderr value=True * +3. `kind` == stdout + *`out` = > json.get value=`obs` key=stdout * + *`tail` = > text_tail_lines text=`out` max_lines=80 max_chars=6000 * + *`obs` = > json.set map=`obs` key=stdout_tail value=`tail` * + *`obs` = > json.set map=`obs` key=read_stdout value=True * +4. `kind` == slots + *`slots` = > json.get value=`obs` key=slots * + *`obs` = > json.set map=`obs` key=slots_detail value=`slots` * + *`obs` = > json.set map=`obs` key=read_slots value=True * +5. * + *`_` = 1* +**`obs`** + +--- + +## compact_plan_observation + + `observation` + +Bounded observation for the parent prompt (actionable, short). + +*`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 * +*`src_len` = 0* +*`has_step` = False* +1. `obs_src` + *`src_len` = > len value=`obs_src` * + *`step_parts` = > split value=`obs_src` sep=worker.step * + *`n_step` = > len value=`step_parts` * + 1. `n_step` > 1 + *`has_step` = True* + 2. * + *`_` = 1* +2. * + *`_` = 1* + +*`compact` = > json.parse text={"note":"Plan-and-Move: CALL/READ then DECISION. Success (exit 0 + has_value) → DONE. solidify_on_done. No long prose."} * +*`compact` = > json.set map=`compact` key=path value=`obs_path` * +*`compact` = > json.set map=`compact` key=exit_code value=`obs_code` * +*`compact` = > json.set map=`compact` key=source_len value=`src_len` * +*`compact` = > json.set map=`compact` key=has_worker_step value=`has_step` * +*`compact` = > json.set map=`compact` key=solidify_on_done value=True * + +1. `obs_src` + *`ex` = > json.get value=`observation` key=source_excerpt * + 1. `ex` + *`compact` = > json.set map=`compact` key=source_excerpt value=`ex` * + 2. * + *`ex` = > workbook_source_excerpt source=`obs_src` * + *`compact` = > json.set map=`compact` key=source_excerpt value=`ex` * +2. * + *`_` = 1* + +1. `obs_stderr` + *`tail` = > json.get value=`observation` key=stderr_tail * + 1. `tail` + *`compact` = > json.set map=`compact` key=stderr_tail value=`tail` * + 2. * + *`tail` = > text_tail_lines text=`obs_stderr` * + *`compact` = > json.set map=`compact` key=stderr_tail value=`tail` * +2. * + *`_` = 1* +1. `obs_stdout` + *`tail` = > json.get value=`observation` key=stdout_tail * + 1. `tail` + *`compact` = > json.set map=`compact` key=stdout_tail value=`tail` * + 2. * + *`tail` = > text_tail_lines text=`obs_stdout` * + *`compact` = > json.set map=`compact` key=stdout_tail value=`tail` * +2. * + *`_` = 1* + +*`val_txt` = > str value=`obs_val` * +*`val_len` = > len value=`val_txt` * +1. `obs_val` + *`compact` = > json.set map=`compact` key=has_value value=True * + *`compact` = > json.set map=`compact` key=value_len value=`val_len` * + 1. `val_len` > 200 + *`preview` = > text_head_lines text=`val_txt` max_lines=4 max_chars=200 * + *`compact` = > json.set map=`compact` key=value_preview value=`preview` * + 2. * + *`compact` = > json.set map=`compact` key=value value=`obs_val` * +2. * + *`compact` = > json.set map=`compact` key=has_value value=False * + +*`slots_brief` = > json.parse text=[] * +1. `obs_slots` + - [`slot`](`obs_slots`) + *`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` = > json.parse text={"key":""} * + *`brief` = > json.set map=`brief` key=key value=`sk` * + *`brief` = > json.set map=`brief` key=line value=`sl` * + *`brief` = > json.set map=`brief` key=body_len value=`sb_len` * + 1. `sk` == error + *`prev` = > text_head_lines text=`sb_txt` max_lines=8 max_chars=400 * + *`brief` = > json.set map=`brief` key=body_preview value=`prev` * + 2. * + *`_` = 1* + *`slots_brief` = > json.append list=`slots_brief` item=`brief` * +2. * + *`_` = 1* +*`compact` = > json.set map=`compact` key=slots value=`slots_brief` * +*`detail` = > json.get value=`observation` key=slots_detail * +1. `detail` + *`compact` = > json.set map=`compact` key=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` = > json.set map=`compact` key=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` = > json.set map=`compact` key=last_error_preview value=`prev` * + *`compact` = > json.set map=`compact` key=last_error_len value=`err_len` * + 2. * + *`compact` = > json.set map=`compact` key=last_error value=`last_error` * +2. * + *`_` = 1* + +**`compact`** + +--- + ## extract_plan_decision + `reply` @@ -314,7 +812,7 @@ First `SUMMARY:` / `汇总:` / `汇总:` line body, else trimmed reply. + `explore_n`=None + `phase`=revise -Parent developer-agent prompt. `phase=decompose`: pre-run (design step ③) before any spawn. `phase=revise` (default): observe → DONE or CONTINUE with patches. +Parent Plan-and-Move prompt. Short protocol only — no long monologues. *`standing` = > json.get value=`agent` key=standing * 1. `standing` @@ -322,115 +820,98 @@ Parent developer-agent prompt. `phase=decompose`: pre-run (design step ③) befo 2. * *`up` = None* -*`skill` = > agent_marqdo_skill * - -Omit full workbook `source` and large slot/value bodies from the parent prompt — they bloat context and invite endless solidify guessing. Runtime `agent_workbook_solidify` runs on DECISION: DONE. - -*`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 * -*`src_len` = 0* -*`has_step` = False* -1. `obs_src` - *`src_len` = > len value=`obs_src` * - *`step_parts` = > split value=`obs_src` sep=worker.step * - *`n_step` = > len value=`step_parts` * - 1. `n_step` > 1 - *`has_step` = True* - 2. * - *`_` = 1* -2. * - *`_` = 1* - -*`compact` = > json.parse text={"note":"source/slot bodies omitted. If exit_code is 0 and has_value, prefer DECISION: DONE immediately — runtime solidifies worker.step. CONTINUE only to fix failures or redesign structure. Never paste user prose into REPLACE."} * -*`compact` = > json.set map=`compact` key=path value=`obs_path` * -*`compact` = > json.set map=`compact` key=exit_code value=`obs_code` * -*`compact` = > json.set map=`compact` key=source_len value=`src_len` * -*`compact` = > json.set map=`compact` key=has_worker_step value=`has_step` * -*`compact` = > json.set map=`compact` key=solidify_on_done value=True * - -*`val_txt` = > str value=`obs_val` * -*`val_len` = > len value=`val_txt` * -1. `obs_val` - *`compact` = > json.set map=`compact` key=has_value value=True * - *`compact` = > json.set map=`compact` key=value_len value=`val_len` * - 1. `val_len` > 200 - *`_` = 1* - 2. * - *`compact` = > json.set map=`compact` key=value value=`obs_val` * -2. * - *`compact` = > json.set map=`compact` key=has_value value=False * - -*`slots_brief` = > json.parse text=[] * -1. `obs_slots` - - [`slot`](`obs_slots`) - *`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` = > json.parse text={"key":""} * - *`brief` = > json.set map=`brief` key=key value=`sk` * - *`brief` = > json.set map=`brief` key=line value=`sl` * - *`brief` = > json.set map=`brief` key=body_len value=`sb_len` * - *`slots_brief` = > json.append list=`slots_brief` item=`brief` * -2. * - *`_` = 1* -*`compact` = > json.set map=`compact` key=slots value=`slots_brief` * - -*`last_ok` = > json.get value=`observation` key=last_ok * -*`last_error` = > json.get value=`observation` key=last_error * -1. `last_ok` - *`ok_txt` = > str value=`last_ok` * - *`ok_len` = > len value=`ok_txt` * - *`compact` = > json.set map=`compact` key=last_ok_len value=`ok_len` * - 1. `ok_len` > 200 - *`compact` = > json.set map=`compact` key=last_ok_omitted value=True * - 2. * - *`compact` = > json.set map=`compact` key=last_ok value=`last_ok` * -2. * - *`_` = 1* -1. `last_error` - *`err_txt` = > str value=`last_error` * - *`err_len` = > len value=`err_txt` * - 1. `err_len` > 200 - *`compact` = > json.set map=`compact` key=last_error_omitted value=True * - *`compact` = > json.set map=`compact` key=last_error_len value=`err_len` * - 2. * - *`compact` = > json.set map=`compact` key=last_error value=`last_error` * -2. * - *`_` = 1* - +*`skill` = > skill_brief * +*`compact` = > compact_plan_observation observation=`observation` * *`obs_s` = > json.stringify value=`compact` * *`goal_s` = > json.stringify value=`goal` * -*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- workbook observation ---\n","d":"\n\n--- marqdo skill ---\n","e_rev":"\n\n--- how to act ---\nYou are a Marqdo agent-development master.\nPriority order (STOP RULES — follow top-down):\n1) SUCCESS STOP: if exit_code is 0 AND has_value is true, reply DECISION: DONE with a one-line SUMMARY immediately. Do NOT invent FIND/REPLACE. Runtime agent_workbook_solidify removes worker.step on DONE — has_worker_step true is NOT a reason to CONTINUE.\n2) FAILURE ONLY: CONTINUE with short FIND/REPLACE (<20 lines) only when exit_code is non-zero, has_value is false, or the returned value clearly fails the goal. Prefer structure edits; never paste itineraries/schedules/observation prose into REPLACE.\n3) Code-first for fixed answers (e.g. pong): solidify via DONE (runtime) or a tiny structural patch — not by rewriting child prose.\n4) If exploring an alternate path, try a meaningfully DIFFERENT structure than prior attempts. Do not merely re-run the same step.\n5) Prefer multiple narrow agents over one giant standing when roles differ.\nNever rewrite the whole .mq.md file.\nThe moment success is observed, emit DONE and stop — do not keep being helpful.\nReply with EXACTLY one protocol:\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","e_dec":"\n\n--- how to act ---\nYou are a Marqdo agent-development master. PRE-RUN DECOMPOSE: the workbook has NOT been executed yet.\nPriority order:\n1) If the skeleton is fine to execute as-is, reply DECISION: RUN (zero patches OK). Prefer RUN over inventing user-facing prose.\n2) Code first: if the goal is a fixed answer, PATCH to a **return** (no worker.step / .单步), then DECISION: RUN or DECISION: DONE with SUMMARY after solidify.\n3) To reshape before the first run, DECISION: CONTINUE with short FIND/REPLACE (<20 lines); runtime applies them then spawns.\n4) Prefer multiple narrow agents when roles differ. Never paste long itineraries into REPLACE.\nNever rewrite the whole .mq.md file.\nReply with EXACTLY one protocol:\nDECISION: RUN\nOR\nDECISION: DONE\nSUMMARY: \nOR\nDECISION: CONTINUE\nPATCH:\n<<<\nFIND\n\n===\nREPLACE\n\n>>>\n(You may repeat <<< blocks.)\n","f":"\n\n--- explore attempt ---\n"} * +*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nREAD:source | stderr | stdout | slots\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning).\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\nPATCH with FIND/REPLACE fences\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning).\n1) Skeleton OK → DECISION: RUN.\n2) Need evidence → READ:source or CALL:workbook_read / lib_catalog.\n3) Reshape → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\nPATCH with FIND/REPLACE fences\n","f":"\n\n--- explore ---\n"} * *`a` = > json.get value=`esc` key=a * *`b` = > json.get value=`esc` key=b * *`c` = > json.get value=`esc` key=c * *`d` = > json.get value=`esc` key=d * +*`tools` = > json.get value=`esc` key=tools * *`f` = > json.get value=`esc` key=f * 1. `phase` == decompose *`e` = > json.get value=`esc` key=e_dec * - *`p` = You decompose the workbook before the first run. * + *`p` = Plan-and-Move: decompose before first run. * 2. * *`e` = > json.get value=`esc` key=e_rev * - *`p` = You develop and revise Marqdo workbooks with surgical patches. * -*`p` = `p` + `a` + `up` + `b` + `goal_s` + `c` + `obs_s` + `d` + `skill` + `e` * + *`p` = Plan-and-Move: revise after child run. * +*`p` = `p` + `a` + `up` + `b` + `goal_s` + `c` + `obs_s` + `tools` + `d` + `skill` + `e` * 1. `explore_attempt` *`p` = `p` + `f` * *`p` = `p` + Attempt * *`p` = `p` + `explore_attempt` * *`p` = `p` + of * *`p` = `p` + `explore_n` * - *`p` = `p` + . Try a different path; prefer code when the answer is fixed. * + *`p` = `p` + . Different path; prefer code when fixed. * 2. * *`_` = 1* **`p`** --- +## plan_llm_act_loop + + `agent` + + `goal` + + `path` + + `observation` + + `phase`=revise + + `explore_attempt`=None + + `explore_n`=None + + `stream`=False + + `echo`=False + + `events` + + `max_acts`=6 + +LLM Plan → CALL/READ/DECISION loop. Returns `{decision,reply,observation,events}`. + +*`model` = > json.get value=`agent` key=model * +*`last_obs` = `observation` * +*`left` = `max_acts` * +*`decision` = None* +*`last_reply` = None* +*`evs_all` = `events` * + +- `left` > 0 + 1. `decision` + *`left` = 0* + 2. * + *`ctx` = > build_plan_context agent=`agent` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=`phase` * + 1. `stream` + *`evs` = > `model`.complete prompt=`ctx` stream=True echo=`echo` * + *`last_reply` = > llm.stream_result events=`evs` * + *`evs_all` = > plan_merge_deltas events=`evs_all` from=`evs` stream=`stream` * + 2. * + *`last_reply` = > `model`.complete prompt=`ctx` * + *`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. `kind` == call + *`tool_out` = > run_parent_tool name=`name` path=`path` observation=`last_obs` reply=`last_reply` * + *`last_obs` = > json.set map=`last_obs` key=tool_result value=`tool_out` * + *`left` = `left` - 1* + 2. `kind` == read + *`last_obs` = > plan_read_deepen observation=`last_obs` kind=`name` path=`path` * + *`left` = `left` - 1* + 3. `kind` == decision + *`decision` = `name`* + *`evs_all` = > plan_append_decision events=`evs_all` decision=`decision` stream=`stream` * + *`left` = 0* + 4. * + *`decision` = unknown* + *`left` = 0* + +*`out` = > json.parse text={} * +*`out` = > json.set map=`out` key=decision value=`decision` * +*`out` = > json.set map=`out` key=reply value=`last_reply` * +*`out` = > json.set map=`out` key=observation value=`last_obs` * +*`out` = > json.set map=`out` key=events value=`evs_all` * +**`out`** + +--- + ## plan_echo_decompose + `workbook` + `stream`=False @@ -912,16 +1393,11 @@ Non-hit path runs parent **decompose** before the first child spawn (`DECISION: > plan_echo_decompose workbook=`path` stream=`stream` echo=`echo` *`last_obs` = > inspect_workbook path=`path` * -*`ctx` = > build_plan_context agent=`self` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=decompose * -1. `stream` - *`evs` = > `model`.complete prompt=`ctx` stream=True echo=`echo` * - *`last_reply` = > llm.stream_result events=`evs` * - *`events` = > plan_merge_deltas events=`events` from=`evs` stream=`stream` * -2. * - *`last_reply` = > `model`.complete prompt=`ctx` * -*`last_reply` = > trim value=`last_reply` * -*`dec` = > extract_plan_decision reply=`last_reply` * -*`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` * +*`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 * 1. `dec` == CONTINUE *`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` * @@ -997,16 +1473,11 @@ Deterministic success stop (loop engineering): when the child already returned a *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` summary=`summary` * *`left` = 0* 2. * - *`ctx` = > build_plan_context agent=`self` goal=`goal` observation=`last_obs` explore_attempt=`explore_attempt` explore_n=`explore_n` phase=revise * - 1. `stream` - *`evs` = > `model`.complete prompt=`ctx` stream=True echo=`echo` * - *`last_reply` = > llm.stream_result events=`evs` * - *`events` = > plan_merge_deltas events=`events` from=`evs` stream=`stream` * - 2. * - *`last_reply` = > `model`.complete prompt=`ctx` * - *`last_reply` = > trim value=`last_reply` * - *`dec` = > extract_plan_decision reply=`last_reply` * - *`events` = > plan_append_decision events=`events` decision=`dec` stream=`stream` * + *`turn` = > plan_llm_act_loop agent=`self` goal=`goal` path=`path` observation=`last_obs` phase=revise 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 * 1. `dec` == DONE > agent_workbook_solidify path=`path` observation=`last_obs` *`done` = 1* diff --git a/lib/subtask.mq.md b/lib/subtask.mq.md index d53cb04..b95b304 100644 --- a/lib/subtask.mq.md +++ b/lib/subtask.mq.md @@ -13,8 +13,10 @@ description: Concurrent subtasks — file, function, or foreign code + `stdin`=None + `quiet`=True -File children are silent by default; set `quiet=False` to inherit parent stdout/stderr. -File `wait` returns `{code, value}` where `value` is the child's `# main` return (not stdout). +File children are silent by default (`quiet=True`: piped capture, no TTY noise). +Set `quiet=False` to inherit parent stdout/stderr. +File `wait` returns `{code, value}` plus optional `stdout`/`stderr` tails when quiet-captured. +`value` is the child's `# main` return (not stdout). **> host_subtask_spawn path=`path` fn=`fn` args=`args` code=`code` lang=`lang` source=`source` stdin=`stdin` quiet=`quiet`** diff --git a/lib/子任务.mq.md b/lib/子任务.mq.md index bf86773..8621e1f 100644 --- a/lib/子任务.mq.md +++ b/lib/子任务.mq.md @@ -13,8 +13,9 @@ description: 并发子任务 — 文件、函数或外联代码 + `输入`=None + `静默`=True -文件子任务默认静默;`静默=假` 时继承父进程终端输出。 -文件 `等待` 返回 `{code, value}`,`value` 为子 `# main` 返回值(不是 stdout)。 +文件子任务默认静默(`静默=真`:管道捕获 stdout/stderr,不污染父终端)。 +`静默=假` 时继承父进程终端输出。 +文件 `等待` 返回 `{code, value}`,静默捕获时另含截断的 `stdout`/`stderr`;`value` 为子 `# main` 返回值。 **> host_subtask_spawn path=`路径` fn=`函数` args=`参数` code=`代码` lang=`语言` source=`源码` stdin=`输入` quiet=`静默`** diff --git a/src/host/subtask.rs b/src/host/subtask.rs index 08e8043..30742c9 100644 --- a/src/host/subtask.rs +++ b/src/host/subtask.rs @@ -2,11 +2,15 @@ //! Parent `HostContext` drop kills/waits file & foreign children; function threads detach. use std::collections::HashMap; +use std::io::Read; use std::path::PathBuf; use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; +/// Cap for file-child stdout/stderr returned on `wait` (parent observation). +const FILE_IO_CAP: usize = 8 * 1024; + use crate::host::foreign; use crate::host::HostContext; use crate::interp::Interpreter; @@ -33,6 +37,9 @@ impl std::fmt::Debug for Handle { pub(crate) struct FileTask { child: Child, result_path: PathBuf, + /// Present when `quiet=True` (piped capture). Absent when inheriting TTY. + stdout: Option>, + stderr: Option>, } pub(crate) struct ForeignTask { @@ -129,6 +136,12 @@ pub fn kill_all(ctx: &mut HostContext) { Handle::File(mut task) => { let _ = task.child.kill(); let _ = task.child.wait(); + if let Some(h) = task.stdout.take() { + let _ = h.join(); + } + if let Some(h) = task.stderr.take() { + let _ = h.join(); + } let _ = std::fs::remove_file(&task.result_path); } Handle::Foreign(mut task) => { @@ -225,9 +238,11 @@ fn spawn_file( None | Some(Value::None) => true, Some(v) => v.truthy(), }; + // quiet: pipe-capture for parent observation (no TTY noise). + // !quiet: inherit parent TTY; wait map omits stdout/stderr bodies. if quiet { - cmd.stdout(Stdio::null()); - cmd.stderr(Stdio::null()); + cmd.stdout(Stdio::piped()); + cmd.stderr(Stdio::piped()); } else { cmd.stdout(Stdio::inherit()); cmd.stderr(Stdio::inherit()); @@ -237,14 +252,37 @@ fn spawn_file( cmd.arg(as_text(item, "arg")?); } } - let child = cmd + let mut child = cmd .spawn() .map_err(|e| format!("subtask spawn {}: {e}", file.display()))?; + let (stdout, stderr) = if quiet { + let mut stdout_pipe = child.stdout.take(); + let mut stderr_pipe = child.stderr.take(); + let stdout = thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(ref mut r) = stdout_pipe { + let _ = r.read_to_end(&mut buf); + } + String::from_utf8_lossy(&buf).into_owned() + }); + let stderr = thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(ref mut r) = stderr_pipe { + let _ = r.read_to_end(&mut buf); + } + String::from_utf8_lossy(&buf).into_owned() + }); + (Some(stdout), Some(stderr)) + } else { + (None, None) + }; ctx.subtasks.insert( id, Handle::File(FileTask { child, result_path, + stdout, + stderr, }), ); Ok(Value::Int(id as i64)) @@ -414,10 +452,27 @@ pub fn join(ctx: &mut HostContext, id: &Value) -> Result { let code = status.code().unwrap_or(-1) as i64; let value = read_emitted_result(&task.result_path); let _ = std::fs::remove_file(&task.result_path); - Ok(Value::Map(vec![ + let stdout = task + .stdout + .take() + .map(|h| h.join().unwrap_or_default()) + .unwrap_or_default(); + let stderr = task + .stderr + .take() + .map(|h| h.join().unwrap_or_default()) + .unwrap_or_default(); + let mut pairs = vec![ ("code".into(), Value::Int(code)), ("value".into(), value), - ])) + ]; + if !stdout.is_empty() { + pairs.push(("stdout".into(), Value::Text(clip_io(&stdout)))); + } + if !stderr.is_empty() { + pairs.push(("stderr".into(), Value::Text(clip_io(&stderr)))); + } + Ok(Value::Map(pairs)) } Handle::Foreign(task) => join_foreign(task), Handle::Function(task) => join_function(task), @@ -492,6 +547,12 @@ pub fn kill(ctx: &mut HostContext, id: &Value) -> Result { .kill() .map_err(|e| format!("subtask kill: {e}"))?; let _ = task.child.wait(); + if let Some(h) = task.stdout.take() { + let _ = h.join(); + } + if let Some(h) = task.stderr.take() { + let _ = h.join(); + } let _ = std::fs::remove_file(&task.result_path); } Handle::Foreign(mut task) => { @@ -522,6 +583,16 @@ pub fn wait_all(ctx: &mut HostContext) -> Result { Ok(Value::List(results)) } +fn clip_io(s: &str) -> String { + let mut it = s.chars(); + let head: String = it.by_ref().take(FILE_IO_CAP).collect(); + if it.next().is_some() { + format!("{head}\n…(truncated)") + } else { + head + } +} + fn require<'a>(bound: &'a HashMap, key: &str) -> Result<&'a Value, String> { bound .get(key) diff --git a/tests/ext/agent-plan-decision.mq.md b/tests/ext/agent-plan-decision.mq.md index dc9bb29..43bee23 100644 --- a/tests/ext/agent-plan-decision.mq.md +++ b/tests/ext/agent-plan-decision.mq.md @@ -31,6 +31,33 @@ description: extract_plan_decision/summary; dual skeleton contains research+writ *`r5` = > agent.extract_plan_decision reply=`d5` * > print text=`r5` +*`act_call` = CALL:lib_catalog * +*`a1` = > agent.extract_plan_act reply=`act_call` * +*`a1k` = > json.get value=`a1` key=kind * +*`a1n` = > json.get value=`a1` key=name * +> print text=`a1k` +> print text=`a1n` + +*`act_read` = READ:stderr * +*`a2` = > agent.extract_plan_act reply=`act_read` * +*`a2k` = > json.get value=`a2` key=kind * +*`a2n` = > json.get value=`a2` key=name * +> print text=`a2k` +> print text=`a2n` + +*`act_dec` = > json.get value=`samples` key=done * +*`a3` = > agent.extract_plan_act reply=`act_dec` * +*`a3k` = > json.get value=`a3` key=kind * +> print text=`a3k` + +*`cat` = > agent.lib_catalog * +*`files` = > json.get value=`cat` key=files * +*`nf` = > len value=`files` * +1. `nf` > 5 + > print text=catalog-ok +2. * + > print text=catalog-bad + *`dual` = > agent.render_workbook_skeleton goal=demo skeleton=dual * *`has_r` = > split value=`dual` sep=research * *`n_r` = > len value=`has_r` * diff --git a/tests/ext/agent-plan-observe.mq.md b/tests/ext/agent-plan-observe.mq.md new file mode 100644 index 0000000..91e48d0 --- /dev/null +++ b/tests/ext/agent-plan-observe.mq.md @@ -0,0 +1,37 @@ +--- +title: parent observation excerpt + deepen (offline) +> ext/ai/agent.mq.md +> lib/json.mq.md +> lib/fs.mq.md +--- + +# main + +*`paths` = > json.parse text={"p":".marqdo/agent-runs/observe-fixture.mq.md"} * +*`path` = > json.get value=`paths` key=p * +*`seed` = > json.parse text={"t":"---\ntitle: fixture\n---\n\n# main\n\n\n\n**ok**\n"} * +*`text` = > json.get value=`seed` key=t * +> fs.write_text path=`path` text=`text` + +*`obs` = > agent.inspect_workbook path=`path` exit_code=0 value=ok * +*`compact` = > agent.compact_plan_observation observation=`obs` * +*`ex` = > json.get value=`compact` key=source_excerpt * +*`parts` = > split value=`ex` sep=HUGE_BODY * +*`n` = > len value=`parts` * +1. `n` == 1 + > print text=excerpt-stripped +2. * + > print text=excerpt-leak + +*`has` = > json.get value=`compact` key=has_value * +1. `has` + > print text=has-value-ok +2. * + > print text=has-value-bad + +*`deep` = > agent.plan_read_deepen observation=`obs` kind=source path=`path` * +*`ex2` = > json.get value=`deep` key=source_excerpt * +1. `ex2` + > print text=read-source-ok +2. * + > print text=read-source-bad diff --git a/tests/gold.rs b/tests/gold.rs index 09d63a9..56f60ae 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1022,6 +1022,11 @@ fn lib_subtask_spawn() { assert_out("tests/lib/subtask-spawn.mq.md", "child_ok\ndone\nquiet-ok"); } +#[test] +fn lib_subtask_quiet_io() { + assert_out("tests/lib/subtask-quiet-io.mq.md", "quiet-io-ok"); +} + #[test] fn lib_subtask_fn() { assert_out("tests/lib/subtask-fn.mq.md", "42"); @@ -1251,7 +1256,15 @@ fn ext_agent_plan_confirm() { fn ext_agent_plan_decision() { assert_out( "tests/ext/agent-plan-decision.mq.md", - "DONE\nall good\nCONTINUE\nDONE\nRUN\nRUN\ndual-ok\nsolidify-ok\n1\nkeep new keep", + "DONE\nall good\nCONTINUE\nDONE\nRUN\nRUN\ncall\nlib_catalog\nread\nstderr\ndecision\ncatalog-ok\ndual-ok\nsolidify-ok\n1\nkeep new keep", + ); +} + +#[test] +fn ext_agent_plan_observe() { + assert_out( + "tests/ext/agent-plan-observe.mq.md", + "excerpt-stripped\nhas-value-ok\nread-source-ok", ); } diff --git a/tests/lib/subtask-child-print.mq.md b/tests/lib/subtask-child-print.mq.md new file mode 100644 index 0000000..73d6331 --- /dev/null +++ b/tests/lib/subtask-child-print.mq.md @@ -0,0 +1,9 @@ +--- +title: subtask child that prints +--- + +# main + +> print text=hello-from-child + +**child_ok** diff --git a/tests/lib/subtask-quiet-io.mq.md b/tests/lib/subtask-quiet-io.mq.md new file mode 100644 index 0000000..4e80c37 --- /dev/null +++ b/tests/lib/subtask-quiet-io.mq.md @@ -0,0 +1,24 @@ +--- +title: quiet file subtask captures stdout/stderr +> lib/subtask.mq.md +> lib/json.mq.md +--- + +# main + +*`id` = > subtask.spawn path=subtask-child-print.mq.md * +*`waited` = > subtask.wait id=`id` * +*`code` = > json.get value=`waited` key=code * +*`val` = > json.get value=`waited` key=value * +*`stdout` = > json.get value=`waited` key=stdout * + +1. `code` == 0 + 1. `val` == "child_ok" + 1. `stdout` + > print text=quiet-io-ok + 2. * + > print text=quiet-io-no-stdout + 2. * + > print text=quiet-io-bad-value +2. * + > print text=quiet-io-fail