pi-suite 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -29
- package/README.zh-CN.md +60 -32
- package/package.json +1 -1
- package/src/agents/index.ts +2 -3
- package/src/agents/render.ts +16 -7
- package/src/agents/schedules/menu.ts +2 -1
- package/src/agents/ui/runs.ts +6 -7
- package/src/agents/ui/types.ts +5 -11
- package/src/agents/viewer-info.ts +11 -9
- package/src/agents/workflow/ui/progress.ts +5 -5
- package/src/ask/view.ts +6 -2
- package/src/jobs/render.ts +11 -3
- package/src/runtime/responses/index.ts +19 -23
- package/src/runtime/responses/payload.ts +10 -7
- package/src/tasks/render.ts +14 -5
- package/src/tasks/tools.ts +5 -2
- package/src/ui/details.ts +16 -4
- package/src/ui/structured-details.ts +57 -11
package/README.md
CHANGED
|
@@ -2,54 +2,82 @@
|
|
|
2
2
|
|
|
3
3
|
[中文](README.zh-CN.md) · [Documentation](docs/en/index.md)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
An all-in-one extension bundle for [Pi](https://github.com/earendil-works/pi), the terminal coding agent, that integrates six standalone extensions into five modules: goals, subagents, user questions, background jobs and task lists. The modules share one storage layer, one notification queue and one panel above the editor (the Dock).
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## Install
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
```sh
|
|
10
|
+
pi install npm:pi-suite
|
|
11
|
+
pi list
|
|
12
|
+
```
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
- **A goal waits for the work it started.** `goal_wait` holds the goal until the listed jobs, subagents or workflows settle, and resumes early on a job monitor event or a subagent question.
|
|
13
|
-
- **Subagents ask their parent.** When a subagent calls `ask_user`, the question goes to the session that started it, which answers with `agent_send`. Questions to you and results of background work never interrupt each other.
|
|
14
|
-
- **One `wait` for everything.** The model waits for any mix of jobs, subagents and workflows with a single call, which also returns when one of them asks a question or a monitor fires.
|
|
15
|
-
- **One notification queue.** Results from all modules are merged into one message per wake-up and delivered only to the session that owns the work. They hold back while a question or browser is open, and while a goal is paused because you cancelled a question.
|
|
16
|
-
- **One Dock.** Goal, tasks, subagents, jobs and workflows share one panel above the editor. Press ← in an empty editor to select a row and open it in the shared browsers: `/tasks`, `/jobs` and `/subagents`, for filtering, reading transcripts and logs, and controlling runs.
|
|
17
|
-
- **Workflows build on the rest.** A workflow script fans out subagents, and each of them can use jobs, tasks and questions like any other subagent.
|
|
14
|
+
Run `/reload` in an open session or restart Pi. All modules are enabled by default. Updates are covered in [Installation](docs/en/installation.md).
|
|
18
15
|
|
|
19
|
-
|
|
16
|
+
The package ships two skills: `pi-suite-jobs` teaches the model to run commands and coding-agent CLIs as jobs, and `pi-suite-workflow` teaches it to write and resume workflow scripts.
|
|
20
17
|
|
|
21
|
-
|
|
22
|
-
| --- | --- | --- |
|
|
23
|
-
| [Ask](docs/en/modules/ask.md) | `pi-ask-user` | `ask_user`: the model asks you one question or a batch of 2–4, with options, defaults, multi-select, free-text answers and an idle timeout. |
|
|
24
|
-
| [Goal](docs/en/modules/goal.md) | `@narumitw/pi-goal` | `/goal <objective>`: the model keeps working across turns until it completes the goal with evidence, reports a blocker, or you pause it. Optional token budget. |
|
|
25
|
-
| [Tasks](docs/en/modules/tasks.md) | `@tintinweb/pi-tasks` | A two-level task list (groups and child tasks) that the model maintains and the Dock displays, with dependencies and atomic batch edits. |
|
|
26
|
-
| [Jobs](docs/en/modules/jobs/index.md) | `pi-background-jobs`, `pi-interactive-shell` | Background commands in pipe or PTY mode: bounded log reading, input, output monitors, coding-agent CLI presets, supervised terminals, and stops that check every captured process has exited and report `unconfirmed` when they cannot. |
|
|
27
|
-
| [Agents](docs/en/modules/agents/index.md) | `@tintinweb/pi-subagents` | Subagents as child Pi sessions in the same process: custom types, per-type models and thinking, `@handle` mentions, questions to the parent, automatic resume after network or upstream errors, schedules, scripted [workflows](docs/en/modules/agents/workflows.md) and an [RPC API](docs/en/modules/agents/rpc.md) for other extensions. |
|
|
18
|
+
## Modules
|
|
28
19
|
|
|
29
|
-
|
|
20
|
+
| Module | Upstream |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| [Goal](docs/en/modules/goal.md) | `@narumitw/pi-goal` |
|
|
23
|
+
| [Agents](docs/en/modules/agents/index.md) | `@tintinweb/pi-subagents` |
|
|
24
|
+
| [Ask](docs/en/modules/ask.md) | `pi-ask-user` |
|
|
25
|
+
| [Jobs](docs/en/modules/jobs/index.md) | `pi-background-jobs`, `pi-interactive-shell` |
|
|
26
|
+
| [Tasks](docs/en/modules/tasks.md) | `@tintinweb/pi-tasks` |
|
|
30
27
|
|
|
31
|
-
|
|
28
|
+
### Goal
|
|
32
29
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
`/goal <objective>` sets one objective for the session. The model keeps working across turns until it completes the goal with evidence (`goal_complete`), reports a blocker (`goal_blocked`), or you pause it. `--tokens 100k` sets an optional token budget. `goal_wait` waits for jobs, subagents and workflows in the same way as `wait` (see [Agents](#agents)).
|
|
31
|
+
|
|
32
|
+
### Agents
|
|
33
|
+
|
|
34
|
+
Subagents are child Pi sessions that run in the same process, in the foreground or background.
|
|
35
|
+
|
|
36
|
+
- **Types**: the built-in `general-purpose`, `Explore` and `Plan`, plus custom types defined by a Markdown file in `~/.pi/agent/agents/` (user) or `.pi/agents/` (project). A type sets the system prompt, tools, model, thinking level, turn limit, skills and persistent memory; `agents.types` overrides the model and thinking of any type. See [Agent types, models and resources](docs/en/modules/agents/types-and-models.md).
|
|
37
|
+
- **Mentions**: `@<type> <message>` in the editor, for example `@explore where is the config loaded?`, hands the message to a subagent of that type.
|
|
38
|
+
- **Questions**: a subagent's `ask_user` question goes to the session that started it.
|
|
39
|
+
- **Recovery**: a subagent stopped by a network or upstream error is resumed in the same session.
|
|
40
|
+
- **Waiting**: `wait` waits for any mix of jobs, subagents and workflows, and returns early when a monitor fires or a subagent asks a question.
|
|
37
41
|
|
|
38
|
-
|
|
42
|
+
Subagents can also run on a [schedule](docs/en/modules/agents/schedules.md). A [workflow](docs/en/modules/agents/workflows.md) script fans out many subagents and can resume from an earlier run. Other extensions start and control subagents through the [RPC API](docs/en/modules/agents/rpc.md).
|
|
43
|
+
|
|
44
|
+
### Ask
|
|
45
|
+
|
|
46
|
+
`ask_user` lets the model ask you one question or a batch of 2–4, with options, defaults, multi-select, free-text answers and an idle timeout (`ask.timeout`).
|
|
47
|
+
|
|
48
|
+
### Jobs
|
|
49
|
+
|
|
50
|
+
Jobs run commands in the background in pipe or PTY mode. The model reads bounded log slices, sends input, and sets output monitors that wake it on a literal, regex or numeric threshold match. In `/jobs` you can read the logs or take over a PTY with `i`.
|
|
51
|
+
|
|
52
|
+
Presets start coding-agent CLIs in a PTY. The model supervises them hands-free, and you can take over the terminal at any time. See [CLI presets and PTY supervision](docs/en/modules/jobs/cli-and-hands-free.md).
|
|
53
|
+
|
|
54
|
+
Stopping a job checks that every captured process has exited, and reports `unconfirmed` when it cannot.
|
|
55
|
+
|
|
56
|
+
### Tasks
|
|
57
|
+
|
|
58
|
+
A two-level task list (groups and child tasks) that the model maintains and the Dock displays, with dependencies and atomic batch edits. A job or subagent can be linked to a task, and a subagent started for a task can update it.
|
|
59
|
+
|
|
60
|
+
## Interface
|
|
61
|
+
|
|
62
|
+
The Dock shows the goal, tasks, subagents, jobs and workflows; press ← in an empty editor to select a row. `/tasks`, `/jobs` and `/subagents` share one browser layout, whose detail pane colors names, IDs, states and errors.
|
|
63
|
+
|
|
64
|
+
Each suite tool call and notification takes one line and expands to labeled fields; a failed tool shows the first line of its error. Results from all modules are merged into one notification per wake-up and delivered only to the session that owns the work.
|
|
65
|
+
|
|
66
|
+
Commands in Pi's built-in `bash` / `powershell` calls and in jobs are highlighted by structure: program, options, variables, strings, operators and redirections. The highlighter only scans the text and never runs the command.
|
|
67
|
+
|
|
68
|
+
The package also includes the `oh-my-pi` dark theme, and makes Pi's copy work inside tmux through OSC 52. See [Interface](docs/en/interface.md).
|
|
39
69
|
|
|
40
70
|
## Commands
|
|
41
71
|
|
|
42
72
|
| Command | What it does |
|
|
43
73
|
| --- | --- |
|
|
44
|
-
| `/goal [--tokens 100k] <objective>` | Starts a goal
|
|
74
|
+
| `/goal [--tokens 100k] <objective>` | Starts a goal. `/goal status`, `edit`, `pause`, `resume` and `clear` show, change, pause, resume or clear it. |
|
|
45
75
|
| `/tasks [group ID]` | Browse the task list, optionally opening one group. |
|
|
46
76
|
| `/jobs [finished\|all] [workspace]` | Browse jobs, read logs, or take over a PTY with `i`. Lists active jobs of this session by default. |
|
|
47
77
|
| `/subagents [queued\|finished\|all\|types\|schedules\|workflows]` | Browse subagent runs, transcripts, types, schedules and workflows; `/subagents workspace [...]` covers the whole workspace. |
|
|
48
78
|
| `/suite` | View and edit settings one by one. |
|
|
49
79
|
| `/exit` | Quit Pi after stopping jobs and subagents and waiting for cleanup, up to 10 seconds for jobs. |
|
|
50
80
|
|
|
51
|
-
Type `@<type>` in the editor (for example `@explore where is the config loaded?`) to hand the message to a subagent of that type.
|
|
52
|
-
|
|
53
81
|
## Settings
|
|
54
82
|
|
|
55
83
|
No configuration is required. Optional settings live in `~/.pi/agent/pi-suite.json` (user) and `.pi/pi-suite.json` (project); the project file overrides the user file field by field. Common settings:
|
|
@@ -68,7 +96,7 @@ No configuration is required. Optional settings live in `~/.pi/agent/pi-suite.js
|
|
|
68
96
|
| `agents.defaultModel`, `agents.types` | unset | Default subagent model; per-type model, thinking and enabled overrides. |
|
|
69
97
|
| `agents.mentions`, `agents.scheduling`, `agents.workflows` | `true` | `@handle` mentions, schedules and workflows. |
|
|
70
98
|
| `jobs.detachKey`, `jobs.returnKey`, `jobs.transferKey` | `ctrl+]`, `ctrl+g`, `ctrl+t` | Leave the terminal view, hand input back to the model, send the screen. |
|
|
71
|
-
| `runtime.openAIResponsesAutoRecovery` | `false` |
|
|
99
|
+
| `runtime.openAIResponsesAutoRecovery` | `false` | When an OpenAI Responses endpoint rejects history created under another upstream account (for example behind a gateway), drop the rejected item IDs or encrypted reasoning and continue. See [OpenAI Responses recovery](docs/en/configuration.md#openai-responses-recovery). |
|
|
72
100
|
|
|
73
101
|
```json
|
|
74
102
|
{
|
package/README.zh-CN.md
CHANGED
|
@@ -2,54 +2,82 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.md) · [文档](docs/zh/index.md)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[Pi](https://github.com/earendil-works/pi)(终端编码 agent)的扩展整合包,把六个独立扩展整合为五个模块:目标、子代理、用户提问、后台任务和任务清单。各模块共用一套存储层、通知队列和编辑器上方的面板(Dock)。
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
## 安装
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
```sh
|
|
10
|
+
pi install npm:pi-suite
|
|
11
|
+
pi list
|
|
12
|
+
```
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
- **目标等待自己发起的工作。** `goal_wait` 让目标停下,直到列出的 job、子代理或 workflow 全部结束;job 监视器触发或子代理提问时会提前恢复。
|
|
13
|
-
- **子代理向父级提问。** 子代理调用 `ask_user` 时,问题发给启动它的会话,由该会话用 `agent_send` 回答。向你的提问和后台工作的结果互不打断。
|
|
14
|
-
- **一个 `wait` 等待所有对象。** 模型一次调用就能等待任意组合的 job、子代理和 workflow;其中有对象提问或监视器触发时也会返回。
|
|
15
|
-
- **一条通知队列。** 各模块的结果每次唤醒合并为一条消息,只投递给拥有该工作的会话。有提问或浏览器打开时会暂缓投递;因你取消提问而暂停的目标也会暂缓,等你发下一条消息时一起送达。
|
|
16
|
-
- **一个 Dock。** 目标、任务、子代理、job 和 workflow 共用编辑器上方的一个面板。在空编辑器中按 ← 可选择某一行,并在共用的浏览器中打开:`/tasks`、`/jobs` 和 `/subagents`,用于筛选、阅读对话记录和日志,以及控制运行。
|
|
17
|
-
- **Workflow 建立在其他模块之上。** Workflow 脚本批量派出子代理,每个子代理都能像普通子代理一样使用 job、任务和提问。
|
|
14
|
+
在已打开的会话中执行 `/reload`,或重启 Pi。所有模块默认启用。更新方式见[安装](docs/zh/installation.md)。
|
|
18
15
|
|
|
19
|
-
|
|
16
|
+
扩展包附带两个技能:`pi-suite-jobs` 指导模型以 job 形式运行命令和编码 agent CLI,`pi-suite-workflow` 指导模型编写和续跑 workflow 脚本。
|
|
20
17
|
|
|
21
|
-
|
|
22
|
-
| --- | --- | --- |
|
|
23
|
-
| [Ask](docs/zh/modules/ask.md) | `pi-ask-user` | `ask_user`:模型向你提出单个问题或 2–4 个批量问题,支持选项、默认值、多选、自由文字回答和空闲超时。 |
|
|
24
|
-
| [Goal](docs/zh/modules/goal.md) | `@narumitw/pi-goal` | `/goal <目标>`:模型跨轮次持续工作,直到附证据完成目标、报告阻塞,或由你暂停。可设置 token 预算。 |
|
|
25
|
-
| [Tasks](docs/zh/modules/tasks.md) | `@tintinweb/pi-tasks` | 两级任务清单(分组与子任务),由模型维护、在 Dock 中显示,支持依赖和原子批量编辑。 |
|
|
26
|
-
| [Jobs](docs/zh/modules/jobs/index.md) | `pi-background-jobs`、`pi-interactive-shell` | pipe 或 PTY 模式的后台命令:有界日志读取、输入、输出监视器、编码 agent CLI 预设、受监督终端;停止时逐一检查已捕获的进程是否退出,无法确认时报告 `unconfirmed`。 |
|
|
27
|
-
| [Agents](docs/zh/modules/agents/index.md) | `@tintinweb/pi-subagents` | 在同一进程中以 Pi 子会话运行的子代理:自定义类型、按类型配置模型与 thinking、`@handle` 提及、向父级提问、网络或上游错误后自动恢复、定时调度、脚本化 [Workflow](docs/zh/modules/agents/workflows.md),以及供其他扩展使用的 [RPC 接口](docs/zh/modules/agents/rpc.md)。 |
|
|
18
|
+
## 模块
|
|
28
19
|
|
|
29
|
-
|
|
20
|
+
| 模块 | 上游来源 |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| [Goal](docs/zh/modules/goal.md) | `@narumitw/pi-goal` |
|
|
23
|
+
| [Agents](docs/zh/modules/agents/index.md) | `@tintinweb/pi-subagents` |
|
|
24
|
+
| [Ask](docs/zh/modules/ask.md) | `pi-ask-user` |
|
|
25
|
+
| [Jobs](docs/zh/modules/jobs/index.md) | `pi-background-jobs`、`pi-interactive-shell` |
|
|
26
|
+
| [Tasks](docs/zh/modules/tasks.md) | `@tintinweb/pi-tasks` |
|
|
30
27
|
|
|
31
|
-
|
|
28
|
+
### Goal
|
|
32
29
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
`/goal <目标>` 为当前会话设定一个目标。模型跨轮次持续工作,直到附证据完成目标(`goal_complete`)、报告阻塞(`goal_blocked`),或由你暂停。`--tokens 100k` 可设置 token 预算。`goal_wait` 等待 job、子代理和 workflow 的方式与 `wait` 相同(见 [Agents](#agents))。
|
|
31
|
+
|
|
32
|
+
### Agents
|
|
33
|
+
|
|
34
|
+
子代理是在同一进程中运行的 Pi 子会话,可在前台或后台运行。
|
|
35
|
+
|
|
36
|
+
- **类型**:内置 `general-purpose`、`Explore` 和 `Plan`,也可以在 `~/.pi/agent/agents/`(用户级)或 `.pi/agents/`(项目级)用 Markdown 文件定义自定义类型。类型决定系统提示、工具、模型、thinking 级别、轮次上限、技能和持久记忆;`agents.types` 可覆盖任意类型的模型和 thinking。见 [Agent 类型、模型与资源](docs/zh/modules/agents/types-and-models.md)。
|
|
37
|
+
- **提及**:在输入框中输入 `@<类型> <消息>`,例如 `@explore 配置是在哪里加载的?`,消息会交给该类型的子代理。
|
|
38
|
+
- **提问**:子代理的 `ask_user` 问题发给启动它的会话。
|
|
39
|
+
- **恢复**:子代理因网络或上游错误中断后,会在同一会话中继续。
|
|
40
|
+
- **等待**:`wait` 可等待任意组合的 job、子代理和 workflow,监视器触发或子代理提问时提前返回。
|
|
37
41
|
|
|
38
|
-
|
|
42
|
+
子代理还可以按[定时调度](docs/zh/modules/agents/schedules.md)运行。[Workflow](docs/zh/modules/agents/workflows.md) 脚本批量派出子代理,并可从之前的运行继续。其他扩展可通过 [RPC 接口](docs/zh/modules/agents/rpc.md)启动和控制子代理。
|
|
43
|
+
|
|
44
|
+
### Ask
|
|
45
|
+
|
|
46
|
+
`ask_user` 让模型向你提出单个问题或 2–4 个批量问题,支持选项、默认值、多选、自由文字回答和空闲超时(`ask.timeout`)。
|
|
47
|
+
|
|
48
|
+
### Jobs
|
|
49
|
+
|
|
50
|
+
job 以 pipe 或 PTY 模式在后台运行命令。模型可以分段读取有界日志、发送输入,并设置输出监视器,在匹配字面量、正则或数值阈值时被唤醒。在 `/jobs` 中可以阅读日志,或按 `i` 接管 PTY。
|
|
51
|
+
|
|
52
|
+
预设可在 PTY 中启动编码 agent CLI,由模型免手动监督,你也可以随时接管终端。见 [CLI 预设与 PTY 监督](docs/zh/modules/jobs/cli-and-hands-free.md)。
|
|
53
|
+
|
|
54
|
+
停止 job 时会逐一检查已捕获的进程是否退出,无法确认时报告 `unconfirmed`。
|
|
55
|
+
|
|
56
|
+
### Tasks
|
|
57
|
+
|
|
58
|
+
两级任务清单(分组与子任务),由模型维护、在 Dock 中显示,支持依赖和原子批量编辑。job 或子代理可以关联到任务,为某个任务启动的子代理可以更新该任务。
|
|
59
|
+
|
|
60
|
+
## 界面
|
|
61
|
+
|
|
62
|
+
Dock 显示目标、任务、子代理、job 和 workflow;在空编辑器中按 ← 可选择某一行。`/tasks`、`/jobs` 和 `/subagents` 使用同一种浏览布局,详情面板为名称、ID、状态和错误着色。
|
|
63
|
+
|
|
64
|
+
每个套件工具调用和通知只占一行,展开后显示带标签的字段;工具失败时折叠行显示错误的第一行。各模块的结果每次唤醒合并为一条通知,只投递给拥有该工作的会话。
|
|
65
|
+
|
|
66
|
+
Pi 内置 `bash` / `powershell` 调用和 job 中的命令按结构高亮:程序、选项、变量、字符串、运算符和重定向。高亮只扫描文本,从不执行命令。
|
|
67
|
+
|
|
68
|
+
扩展包还提供深色主题 `oh-my-pi`,并使 Pi 的复制在 tmux 中经 OSC 52 转发到本地终端。见[界面](docs/zh/interface.md)。
|
|
39
69
|
|
|
40
70
|
## 命令
|
|
41
71
|
|
|
42
72
|
| 命令 | 作用 |
|
|
43
73
|
| --- | --- |
|
|
44
|
-
| `/goal [--tokens 100k] <目标>` |
|
|
74
|
+
| `/goal [--tokens 100k] <目标>` | 建立目标。`/goal status`、`edit`、`pause`、`resume`、`clear` 查看、修改、暂停、恢复或清除目标。 |
|
|
45
75
|
| `/tasks [组 ID]` | 浏览任务清单,可直接定位到某个组。 |
|
|
46
|
-
| `/jobs [finished\|all] [workspace]` | 浏览 job、阅读日志,或按 `i` 接管 PTY
|
|
76
|
+
| `/jobs [finished\|all] [workspace]` | 浏览 job、阅读日志,或按 `i` 接管 PTY。默认只列当前会话的活动 job。 |
|
|
47
77
|
| `/subagents [queued\|finished\|all\|types\|schedules\|workflows]` | 浏览子代理运行、对话记录、类型、定时调度和 workflow;`/subagents workspace [...]` 查看整个工作区。 |
|
|
48
78
|
| `/suite` | 逐项查看和编辑设置。 |
|
|
49
79
|
| `/exit` | 退出 Pi,先停止 job 和子代理并等待清理,job 最多等待 10 秒。 |
|
|
50
80
|
|
|
51
|
-
在输入框中输入 `@<类型>`(例如 `@explore 配置是在哪里加载的?`)可把消息交给对应类型的子代理。
|
|
52
|
-
|
|
53
81
|
## 设置项
|
|
54
82
|
|
|
55
83
|
无需任何配置。可选设置位于 `~/.pi/agent/pi-suite.json`(用户级)和 `.pi/pi-suite.json`(项目级);项目文件按字段覆盖用户文件。常用设置:
|
|
@@ -68,7 +96,7 @@ pi list
|
|
|
68
96
|
| `agents.defaultModel`、`agents.types` | 未设置 | 子代理默认模型;按类型覆盖模型、thinking 和启用状态。 |
|
|
69
97
|
| `agents.mentions`、`agents.scheduling`、`agents.workflows` | `true` | `@handle` 提及、定时调度和 workflow。 |
|
|
70
98
|
| `jobs.detachKey`、`jobs.returnKey`、`jobs.transferKey` | `ctrl+]`、`ctrl+g`、`ctrl+t` | 终端视图的离开、交还模型和发送屏幕按键。 |
|
|
71
|
-
| `runtime.openAIResponsesAutoRecovery` | `false` |
|
|
99
|
+
| `runtime.openAIResponsesAutoRecovery` | `false` | OpenAI Responses 端点因历史来自其他上游账号(例如经过网关)而拒绝请求时,移除被拒的 item ID 或加密 reasoning 后继续。见 [OpenAI Responses 恢复](docs/zh/configuration.md#openai-responses-恢复)。 |
|
|
72
100
|
|
|
73
101
|
```json
|
|
74
102
|
{
|
|
@@ -77,7 +105,7 @@ pi list
|
|
|
77
105
|
}
|
|
78
106
|
```
|
|
79
107
|
|
|
80
|
-
全部字段见
|
|
108
|
+
全部字段见[配置](docs/zh/configuration.md),也可以用 `/suite` 编辑。
|
|
81
109
|
|
|
82
110
|
## 文档
|
|
83
111
|
|
|
@@ -92,7 +120,7 @@ pnpm typecheck
|
|
|
92
120
|
pnpm test
|
|
93
121
|
```
|
|
94
122
|
|
|
95
|
-
源码结构和项目规则见
|
|
123
|
+
源码结构和项目规则见[开发](docs/zh/development.md)。
|
|
96
124
|
|
|
97
125
|
## 致谢与许可证
|
|
98
126
|
|
package/package.json
CHANGED
package/src/agents/index.ts
CHANGED
|
@@ -27,9 +27,8 @@ export function agentSummary(record: AgentRecord) {
|
|
|
27
27
|
const { prompt, result, ...summary } = record;
|
|
28
28
|
return { ...summary, promptSummary: boundedText(prompt, 200), resultSummary: result === undefined ? undefined : boundedText(result, 500) };
|
|
29
29
|
}
|
|
30
|
-
export function usageText(
|
|
31
|
-
|
|
32
|
-
return usage && `usage: input ${usage.tokens.input} · output ${usage.tokens.output} · cacheRead ${usage.tokens.cacheRead} · cacheWrite ${usage.tokens.cacheWrite} · total ${usage.tokens.total} · cost $${usage.cost.toFixed(6)}`;
|
|
30
|
+
export function usageText({ usage }: Pick<AgentRecord, 'usage'>, prefix = 'usage: '): string | undefined {
|
|
31
|
+
return usage && `${prefix}input ${usage.tokens.input} · output ${usage.tokens.output} · cacheRead ${usage.tokens.cacheRead} · cacheWrite ${usage.tokens.cacheWrite} · total ${usage.tokens.total} · cost $${usage.cost.toFixed(6)}`;
|
|
33
32
|
}
|
|
34
33
|
function resultLines(record: AgentRecord, error = record.error): string[] {
|
|
35
34
|
return [record.error ? usageText(record) : undefined, record.error ? `error: ${error}` : undefined,
|
package/src/agents/render.ts
CHANGED
|
@@ -6,13 +6,15 @@ import type { ReadPage } from '../runtime/read.ts';
|
|
|
6
6
|
import type { StopOutcome } from '../runtime/tools.ts';
|
|
7
7
|
import type { JobSummary } from '../jobs/types.ts';
|
|
8
8
|
import type { ScheduledAgent } from './schedules/store.ts';
|
|
9
|
-
import type {
|
|
9
|
+
import type { AskParams } from '../ask/schema.ts';
|
|
10
|
+
import { usageText, type agentSummary } from './index.ts';
|
|
10
11
|
|
|
11
12
|
type Summary = ReturnType<typeof agentSummary>;
|
|
12
|
-
type Details = { agent: Summary; backgrounded?: boolean; question?:
|
|
13
|
+
type Details = { agent: Summary; backgrounded?: boolean; question?: AskParams };
|
|
13
14
|
type Args = { id: string; runId?: string };
|
|
14
15
|
type StartArgs = { type?: string; name?: string; prompt: string; schedule?: string; background?: boolean };
|
|
15
16
|
function agentFields(agent: Summary): ToolExpandedRow[] {
|
|
17
|
+
const usage = usageText(agent, '');
|
|
16
18
|
return [
|
|
17
19
|
{ label: 'id', value: agent.id }, { label: 'runId', value: agent.runId },
|
|
18
20
|
{ label: 'state', value: agent.state, tone: stateLine(agent.state).tone },
|
|
@@ -22,10 +24,14 @@ function agentFields(agent: Summary): ToolExpandedRow[] {
|
|
|
22
24
|
...agent.taskId ? [{ label: 'taskId', value: agent.taskId }] : [],
|
|
23
25
|
...agent.taskGeneration ? [{ label: 'taskGeneration', value: agent.taskGeneration }] : [],
|
|
24
26
|
...agent.activity ? [{ label: 'activity', value: agent.activity }] : [],
|
|
25
|
-
...
|
|
27
|
+
...usage !== undefined ? [{ label: 'usage', value: usage }] : [],
|
|
26
28
|
...agent.error ? [{ label: 'error', value: agent.error, tone: 'error' as const }] : [],
|
|
27
29
|
];
|
|
28
30
|
}
|
|
31
|
+
function scheduleFields({ request, ...schedule }: ScheduledAgent): ToolExpandedRow[] {
|
|
32
|
+
return [...Object.entries(schedule), ...Object.entries(request).map(([key, value]) => [`request.${key}`, value] as const)]
|
|
33
|
+
.flatMap(([key, value]) => value === undefined ? [] : [{ label: key.toLowerCase(), value: String(value) }]);
|
|
34
|
+
}
|
|
29
35
|
export const startRenderers = toolRenderers<StartArgs, Details | { schedule: ScheduledAgent }>({
|
|
30
36
|
call: args => args.schedule
|
|
31
37
|
? { icon: '⏲', tone: 'accent', title: 'Agent schedule', summary: args.schedule }
|
|
@@ -39,7 +45,7 @@ export const startRenderers = toolRenderers<StartArgs, Details | { schedule: Sch
|
|
|
39
45
|
expanded: data => 'agent' in data ? [...agentFields(data.agent),
|
|
40
46
|
{ label: 'promptSummary', value: data.agent.promptSummary },
|
|
41
47
|
...data.agent.resultSummary !== undefined ? [{ label: 'resultSummary', value: data.agent.resultSummary }] : []]
|
|
42
|
-
:
|
|
48
|
+
: scheduleFields(data.schedule),
|
|
43
49
|
});
|
|
44
50
|
export const listRenderers = toolRenderers<{ agentId?: string; state?: string; scope?: string }, { agents: Summary[]; nextCursor?: string }>({
|
|
45
51
|
call: args => ({ icon: '⟳', tone: 'accent', title: 'Agents', summary: args.agentId ? agentDisplayName(args.agentId) : undefined }),
|
|
@@ -54,10 +60,13 @@ export const getRenderers = toolRenderers<Args & { detail?: boolean }, Details &
|
|
|
54
60
|
collapsed: data => ({ ...stateLine(data.question ? 'waiting(parent)' : data.agent.state), title: data.agent.name,
|
|
55
61
|
meta: [{ text: data.question ? 'question pending' : data.agent.state, tone: stateLine(data.question ? 'waiting(parent)' : data.agent.state).tone! }] }),
|
|
56
62
|
expanded: ({ agent, question, jobs, jobsUnavailable }, args) => [...agentFields(agent),
|
|
57
|
-
...question ?
|
|
63
|
+
...question ? (question.questions ?? [question]).flatMap(item => [
|
|
64
|
+
...item.question !== undefined ? [{ label: 'question', value: item.question }] : [],
|
|
65
|
+
...item.options ? [{ label: 'options', value: item.options.map(option => typeof option === 'string' ? option : option.title).join(', ') }] : [],
|
|
66
|
+
]) : [],
|
|
58
67
|
...args.detail ? [
|
|
59
68
|
{ label: 'modelSource', value: agent.modelSource }, { label: 'thinkingSource', value: agent.thinkingSource },
|
|
60
|
-
...agent.contextUsage ? [{
|
|
69
|
+
...agent.contextUsage ? [{ label: 'contextUsage', value: `${agent.contextUsage.tokens ?? 'unknown'}/${agent.contextUsage.contextWindow} tokens${agent.contextUsage.percent === null ? '' : ` · ${agent.contextUsage.percent.toFixed(1)}%`}` }] : [],
|
|
61
70
|
...agent.lastUpdateAt ? [{ label: 'lastUpdateAt', value: agent.lastUpdateAt }] : [],
|
|
62
71
|
] : [],
|
|
63
72
|
...jobsUnavailable ? [{ label: 'jobsUnavailable', value: jobsUnavailable, tone: 'warning' as const }] : [],
|
|
@@ -81,5 +90,5 @@ export const stopRenderers = toolRenderers<Args, StopOutcome & { runId: string;
|
|
|
81
90
|
...data.affected.length > 1 ? [`+${data.affected.length - 1} affected`] : []] }),
|
|
82
91
|
expanded: data => [{ label: 'runId', value: data.runId }, { label: 'requested', value: String(data.requested) },
|
|
83
92
|
{ label: 'cleanup', value: data.cleanup, tone: ['pending', 'unconfirmed'].includes(data.cleanup) ? 'warning' : 'dim' },
|
|
84
|
-
{
|
|
93
|
+
{ label: 'affected', value: data.affected.map(item => `${item.id}: ${item.state}${item.cleanup ? ` (cleanup ${item.cleanup})` : ''}`).join('\n') }],
|
|
85
94
|
});
|
|
@@ -14,7 +14,8 @@ const details = (job: ScheduledAgent): StructuredDetails => ({rows: [
|
|
|
14
14
|
field('Next:', part(job.nextRun ?? '—', 'meta')),
|
|
15
15
|
field('Last:', part(job.lastRun ?? '—', 'meta'), part(' ('), statePart(job.lastStatus ?? '—'), part(')')),
|
|
16
16
|
field('Runs:', part(job.runCount, 'number')), field('Agent:', part(job.lastAgentId ?? '—', 'id')),
|
|
17
|
-
|
|
17
|
+
job.lastError !== undefined ? field('Error:', part(job.lastError, 'error')) : undefined, null,
|
|
18
|
+
section('Input'), job.request.prompt,
|
|
18
19
|
]});
|
|
19
20
|
|
|
20
21
|
export async function showSchedules(ctx: ExtensionContext, scheduler: AgentScheduler, dock: Dock, page: BrowsePage): Promise<void> {
|
package/src/agents/ui/runs.ts
CHANGED
|
@@ -46,12 +46,11 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
46
46
|
return !agents.manager.visible(record, scope) && (!run || run.settled === true);
|
|
47
47
|
};
|
|
48
48
|
const status = (record: AgentRecord) => agents.manager.runs.get(record.runId)?.question ? 'waiting(parent)' : record.state;
|
|
49
|
-
const suffix = (record: AgentRecord
|
|
49
|
+
const suffix = (record: AgentRecord) => {
|
|
50
50
|
const state = status(record), retry = retrySuffix(agents.manager.runs.get(record.runId));
|
|
51
51
|
const head: DisplayField[] = [{text: state, state}, ...retry ? [{text: retry, tone: 'muted' as const}] : []];
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
return { full, compact: runs.length ? [[...head, ...runs], head] : [head] };
|
|
52
|
+
const full: DisplayField[] = [...head, {text: ` · ${duration(record)}`, tone: 'muted'}];
|
|
53
|
+
return { full, compact: [head] };
|
|
55
54
|
};
|
|
56
55
|
const name = (record: AgentRecord) => history ? record.runId : record.name;
|
|
57
56
|
for (; !exit.closed;) {
|
|
@@ -69,8 +68,8 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
69
68
|
selected: () => state.filter, select: (value, done) => { changed = true; change(value as RunFilter, state.workspace, done); } }],
|
|
70
69
|
subscribe: refresh => agents.manager.subscribe(refresh), ticking: () => [...displayed.values()].some(([record]) => active(record.state)),
|
|
71
70
|
layout: { truncatePrimary: ({item, maxWidth, theme}) => {
|
|
72
|
-
const
|
|
73
|
-
const { full, compact } = suffix(record
|
|
71
|
+
const [record] = displayed.get(item.value)!;
|
|
72
|
+
const { full, compact } = suffix(record);
|
|
74
73
|
return executionRow(sanitizeText(name(record)).replace(/[\r\n\t]/g, ' '), full, compact, maxWidth, theme);
|
|
75
74
|
} },
|
|
76
75
|
items: () => {
|
|
@@ -83,7 +82,7 @@ export async function showRuns(ctx: ExtensionContext, deps: SubagentsDeps, state
|
|
|
83
82
|
.sort(([, [a]], [, [b]]) => compareActivity(a, b, record => active(record.state))));
|
|
84
83
|
return Array.from(displayed, ([value, runs]) => {
|
|
85
84
|
const [record] = runs;
|
|
86
|
-
const display: DisplayField[] = [{text: name(record)}, {text: ' · ', tone: 'muted'}, ...suffix(record
|
|
85
|
+
const display: DisplayField[] = [{text: name(record)}, {text: ' · ', tone: 'muted'}, ...suffix(record).full];
|
|
87
86
|
return { value, status: status(record), label: displayText(display), display,
|
|
88
87
|
search: `${record.id} ${runs.map(run => run.runId).join(' ')} ${record.name} ${record.type} ${record.state} ${record.model} ${record.prompt}`,
|
|
89
88
|
details: () => agentDetails(record, undefined, readonly(record)) };
|
package/src/agents/ui/types.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { resolveSettings } from '../models.ts';
|
|
|
9
9
|
import { editTypeModel } from '../model-editor.ts';
|
|
10
10
|
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
11
11
|
import { sanitizeText } from '../../runtime/text.ts';
|
|
12
|
-
import { field, part, statePart, type DetailRow, type StructuredDetails } from '../../ui/structured-details.ts';
|
|
12
|
+
import { field, part, section, statePart, type DetailRow, type StructuredDetails } from '../../ui/structured-details.ts';
|
|
13
13
|
|
|
14
14
|
export async function showAgentTypes(ctx: ExtensionContext, dock: Dock, config: () => SuiteConfig, reload: (cwd: string) => void, page: BrowsePage): Promise<void> {
|
|
15
15
|
for (; !page.navigation?.closed;) {
|
|
@@ -22,12 +22,7 @@ export async function showAgentTypes(ctx: ExtensionContext, dock: Dock, config:
|
|
|
22
22
|
// Inheritance is a runtime choice, not a type default; never preview the parent's live value as a pin.
|
|
23
23
|
model = resolved.modelSource === 'inherited' ? 'not configured' : `${resolved.model.provider}/${resolved.model.id}`;
|
|
24
24
|
thinking = resolved.thinkingSource === 'inherited' ? 'not configured' : clampThinkingLevel(resolved.model, resolved.thinking);
|
|
25
|
-
settings = [
|
|
26
|
-
field('Model:', model, part(` (${resolved.modelSource})`, 'meta'),
|
|
27
|
-
part(resolved.modelSource === 'inherited' ? ' · inherit from parent at start' : '')),
|
|
28
|
-
field('Thinking:', thinking, part(` (${resolved.thinkingSource})`, 'meta'),
|
|
29
|
-
part(resolved.thinkingSource === 'inherited' ? ' · inherit from parent at start, adjusted to model capabilities' : '')),
|
|
30
|
-
];
|
|
25
|
+
settings = [field('Model:', `${model} · ${thinking}`)];
|
|
31
26
|
} catch (error) {
|
|
32
27
|
// Invalid model pins remain visible and editable; report the exact failure in details.
|
|
33
28
|
settings = [field('Configuration error:', part(error instanceof Error ? error.message : String(error), 'error'))];
|
|
@@ -36,9 +31,8 @@ export async function showAgentTypes(ctx: ExtensionContext, dock: Dock, config:
|
|
|
36
31
|
return { value: type.name, status: type.enabled === false ? 'disabled' : 'enabled', modelId: model.slice(model.indexOf('/') + 1), thinking, enabled: type.enabled !== false,
|
|
37
32
|
label: `${type.name} · ${type.enabled === false ? 'disabled' : 'enabled'} · ${model} · ${thinking}`,
|
|
38
33
|
search: `${type.name} ${type.description} ${model} ${thinking}`, details: (): StructuredDetails => ({rows: [
|
|
39
|
-
[part(type.name, 'heading')],
|
|
40
|
-
field('Enabled:', statePart(type.enabled !== false, type.enabled === false ? 'disabled' : 'enabled'),
|
|
41
|
-
part(` (${current.agents.types[type.name]?.enabled === undefined ? 'definition' : 'configuration'})`, 'meta')), null,
|
|
34
|
+
[part(type.name, 'heading')],
|
|
35
|
+
field('Enabled:', statePart(type.enabled !== false, type.enabled === false ? 'disabled' : 'enabled')), null,
|
|
42
36
|
...settings, null, field('Definition:', part(type.sourcePath ?? 'built-in', 'meta')),
|
|
43
37
|
field('Model settings:', part(locations.model, 'meta')), field('Thinking settings:', part(locations.thinking, 'meta')), null,
|
|
44
38
|
field('Tools:', type.tools?.join(', ') ?? 'inherited'), field('Excluded tools:', type.excludeTools?.join(', ') ?? 'none'),
|
|
@@ -48,7 +42,7 @@ export async function showAgentTypes(ctx: ExtensionContext, dock: Dock, config:
|
|
|
48
42
|
Isolated: type.isolated, Memory: type.memory, Extensions: type.extensions, 'Excluded extensions': type.excludeExtensions,
|
|
49
43
|
Skills: type.skills, Color: type.color }).map(([label, value]) => value === undefined ? undefined
|
|
50
44
|
: field(`${label}:`, part(Array.isArray(value) ? value.join(', ') : String(value), typeof value === 'number' ? 'number' : label === 'Session directory' ? 'meta' : undefined))),
|
|
51
|
-
'', type.systemPrompt]}) };
|
|
45
|
+
null, section('Description'), type.description, section('System prompt'), type.systemPrompt]}) };
|
|
52
46
|
});
|
|
53
47
|
let action = 'model';
|
|
54
48
|
const selected = await browse(ctx, dock, { title: 'Subagents', state: page.state, pages: page.pages, navigation: page.navigation, items: () => items,
|
|
@@ -1,24 +1,26 @@
|
|
|
1
1
|
import type { AgentRecord } from './types.ts';
|
|
2
|
-
import { field, part, section, statePart, type StructuredDetails } from '../ui/structured-details.ts';
|
|
2
|
+
import { field, outputRow, part, section, statePart, type StructuredDetails } from '../ui/structured-details.ts';
|
|
3
|
+
import { countText, elapsedText } from '../ui/format.ts';
|
|
3
4
|
|
|
4
5
|
/** Runtime statistics are run-scoped; current type configuration cannot rewrite history. */
|
|
5
6
|
export function agentDetails(record: AgentRecord, permissions?: {readonly: boolean; canMessage: boolean; canStop: boolean}, readOnlyBanner = false): StructuredDetails {
|
|
6
7
|
const context = record.contextUsage;
|
|
7
8
|
const tokens = record.usage?.tokens;
|
|
9
|
+
// Pi tracks uncached input, cache reads and cache writes as separate prompt token counts.
|
|
10
|
+
const promptTokens = tokens ? tokens.input + tokens.cacheRead + tokens.cacheWrite : 0;
|
|
8
11
|
return {rows: [
|
|
9
12
|
readOnlyBanner ? [part('Read only', 'meta')] : undefined,
|
|
10
13
|
[part(record.name, 'heading')], field('Type:', record.type), field('ID:', part(record.id, 'id')),
|
|
11
|
-
field('
|
|
12
|
-
field('Model:', record.model
|
|
13
|
-
field('Thinking:', record.thinking, part(` (${record.thinkingSource})`, 'meta')), null,
|
|
14
|
+
field('State:', statePart(record.state)), null,
|
|
15
|
+
field('Model:', `${record.model} · ${record.thinking}`), null,
|
|
14
16
|
...(permissions ? [field('Read only:', permissions.readonly), field('Can message:', permissions.canMessage), field('Can stop:', permissions.canStop)] : []),
|
|
15
|
-
field('Owner session:', part(record.ownerSessionId, 'id')),
|
|
16
17
|
record.parentRunId ? field('Parent run:', part(record.parentRunId, 'id')) : undefined, null,
|
|
17
|
-
tokens ? field('Tokens:', part(`input ${tokens.input} · output ${tokens.output} · cache read ${tokens.cacheRead} · cache write ${tokens.cacheWrite} · total ${tokens.total}`, 'number')) : undefined,
|
|
18
|
+
tokens ? field('Tokens:', part(`input ${countText(tokens.input)} · output ${countText(tokens.output)} · cache read ${countText(tokens.cacheRead)} · cache write ${countText(tokens.cacheWrite)} · total ${countText(tokens.total)}`, 'number')) : undefined,
|
|
19
|
+
tokens ? field('Cache hit rate:', promptTokens > 0 ? part(`${(tokens.cacheRead / promptTokens * 100).toFixed(1)}%`, 'number') : 'unavailable') : undefined,
|
|
18
20
|
record.usage ? field('Cost:', part(`$${record.usage.cost.toFixed(6)}`, 'number')) : undefined,
|
|
19
21
|
field('Context:', context ? part(`${context.tokens ?? 'unknown'} / ${context.contextWindow} tokens${context.percent === null ? '' : ` (${context.percent.toFixed(1)}%)`}`, 'number') : 'unavailable'),
|
|
20
22
|
field('Tool calls:', part(record.toolUses ?? (record.state === 'queued' || record.state === 'starting' ? 0 : 'unavailable'), 'number')), null,
|
|
21
|
-
field('Runtime:', record.elapsedMs === undefined ? 'not started' : part(
|
|
23
|
+
field('Runtime:', record.elapsedMs === undefined ? 'not started' : part(elapsedText(record.elapsedMs), 'number')),
|
|
22
24
|
record.state === 'queued' ? field('Queued:', part(`${Math.max(0, Date.now() - Date.parse(record.createdAt)) / 1000}s`, 'number')) : undefined,
|
|
23
25
|
field('Created:', part(record.createdAt, 'meta')),
|
|
24
26
|
record.startedAt ? field('Started:', part(record.startedAt, 'meta')) : undefined,
|
|
@@ -27,10 +29,10 @@ export function agentDetails(record: AgentRecord, permissions?: {readonly: boole
|
|
|
27
29
|
record.workflowId ? field('Workflow:', part(record.workflowId, 'id')) : undefined, null,
|
|
28
30
|
] : []),
|
|
29
31
|
record.endedAt ? field('Ended:', part(record.endedAt, 'meta')) : undefined,
|
|
30
|
-
field('Cwd:', part(record.cwd, 'meta')),
|
|
31
32
|
// Prompt and result are free text; titled sections keep them apart from the fields above.
|
|
32
33
|
section('Input'), record.prompt,
|
|
33
34
|
...(record.result !== undefined || record.error ? [section('Output'),
|
|
34
|
-
record.error ? field('Error:', part(record.error, 'error')) : undefined,
|
|
35
|
+
record.error ? field('Error:', part(record.error, 'error')) : undefined,
|
|
36
|
+
record.result === undefined ? undefined : outputRow(record.result, {markdown: true})] : []),
|
|
35
37
|
]};
|
|
36
38
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import type { Theme } from '@earendil-works/pi-coding-agent';
|
|
4
4
|
import { toolLine, stateLine, type ToolExpandedRow, type ToolLine } from '../../../ui/tool-render.ts';
|
|
5
5
|
import { Text } from '@earendil-works/pi-tui';
|
|
6
|
-
import { detailsText, field, part, statePart, type DetailRow, type StructuredDetails } from '../../../ui/structured-details.ts';
|
|
6
|
+
import { detailsText, field, part, section, statePart, type DetailRow, type StructuredDetails } from '../../../ui/structured-details.ts';
|
|
7
7
|
import { workflowActive } from '../manager.ts';
|
|
8
8
|
import { buildPhaseGroups, displayState, formatDuration, header } from '../progress/index.ts';
|
|
9
9
|
import { workflowResultText, type WorkflowTask } from '../task.ts';
|
|
@@ -12,14 +12,14 @@ export function workflowDetails(task: WorkflowTask, expanded = true, now = Date.
|
|
|
12
12
|
const groups = buildPhaseGroups(task.workflowProgress, task.meta?.phases);
|
|
13
13
|
const title = header(task, task.meta, groups, task.agentCount, now);
|
|
14
14
|
const active = workflowActive(task);
|
|
15
|
-
const rows: DetailRow[] = [
|
|
15
|
+
const rows: (DetailRow | null)[] = [
|
|
16
16
|
[part(title.name, 'heading'), part(' · '), part(title.stats, 'number'), ...(title.state ? [part(' · '), statePart(title.state)] : [])],
|
|
17
17
|
title.subtext,
|
|
18
18
|
[part(`${task.totalTokens} tokens · ${task.totalToolCalls} tools${task.replayedCount ? ` · ${task.replayedCount} replayed` : ''}`, 'number')],
|
|
19
19
|
];
|
|
20
20
|
if (expanded) {
|
|
21
21
|
for (const group of groups) {
|
|
22
|
-
rows.push(
|
|
22
|
+
rows.push(null, [part(group.title, 'heading'), part(' · '), statePart(group.status, group.status === 'not-started' ? 'queued' : group.status),
|
|
23
23
|
part(' · '), part(`${group.doneCount}/${group.totalCount} · ${formatDuration(group.durationMs)}`, 'number')]);
|
|
24
24
|
for (const agent of group.agents) {
|
|
25
25
|
const state = displayState(agent, active);
|
|
@@ -39,8 +39,8 @@ export function workflowDetails(task: WorkflowTask, expanded = true, now = Date.
|
|
|
39
39
|
if (agent.error) rows.push(field(' Error:', part(agent.error, 'error')));
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
|
-
if (task.logs.length) rows.push(
|
|
43
|
-
if (!active) rows.push(
|
|
42
|
+
if (task.logs.length) rows.push(null, section('Logs'), ...task.logs);
|
|
43
|
+
if (!active) rows.push(null, section('Result'), [part(workflowResultText(task), task.error === undefined ? undefined : 'error')]);
|
|
44
44
|
}
|
|
45
45
|
return {rows};
|
|
46
46
|
}
|
package/src/ask/view.ts
CHANGED
|
@@ -268,10 +268,14 @@ export class AskView extends Container {
|
|
|
268
268
|
}
|
|
269
269
|
private editorLines(width: number, height: number): string[] {
|
|
270
270
|
const editor = this.editors[this.form.index]; editor.focused = this.focus === "answer";
|
|
271
|
-
const
|
|
271
|
+
const prompt = "✎ ", promptWidth = visibleWidth(prompt);
|
|
272
|
+
const rendered = editor.render(Math.max(1, width - promptWidth)).slice(1, -1);
|
|
272
273
|
const cursor = rendered.findIndex(line => line.includes(CURSOR_MARKER));
|
|
273
274
|
const start = Math.max(0, cursor - height + 1);
|
|
274
|
-
|
|
275
|
+
const indent = " ".repeat(promptWidth);
|
|
276
|
+
// Decorate the viewport after slicing so the prompt stays at its top as the cursor scrolls.
|
|
277
|
+
return rendered.slice(start, start + height).map((line, index) =>
|
|
278
|
+
(index === 0 ? this.theme.fg("accent", prompt) : indent) + line);
|
|
275
279
|
}
|
|
276
280
|
private answerLine(width: number): string {
|
|
277
281
|
if (this.focus === "search") { this.search.focused = true; return this.search.render(width)[0]; }
|
package/src/jobs/render.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { MessageRenderer } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { Box, truncateToWidth } from '@earendil-works/pi-tui';
|
|
3
3
|
import { sanitizeText } from '../runtime/text.ts';
|
|
4
|
+
import { elapsedText } from '../ui/format.ts';
|
|
4
5
|
import { readingText } from '../ui/reading.ts';
|
|
5
6
|
import { readPageFields } from '../ui/rendering/read-page.ts';
|
|
6
7
|
import { toolRenderers, toolLine, stateLine, type ToolExpandedRow, type ToolLine } from '../ui/tool-render.ts';
|
|
@@ -38,14 +39,22 @@ type WriteDetails = JobDetails & { bytesSent?: number; stdinClosed?: boolean };
|
|
|
38
39
|
const name = (job: JobSummary) => job.name || job.command.split('\n')[0];
|
|
39
40
|
const cleanupTone = (cleanup: string) => cleanup === 'pending' || cleanup === 'unconfirmed' ? 'warning' as const : 'dim' as const;
|
|
40
41
|
function jobFields(job: JobSummary): ToolExpandedRow[] {
|
|
42
|
+
const exit = job.exitCode ?? job.signal;
|
|
41
43
|
return [
|
|
42
44
|
// Jobs execute through Pi's Bash selection (including Git Bash/WSL on Windows).
|
|
43
45
|
{ command: job.command, shell: 'bash', label: 'command' }, { label: 'cwd', value: job.cwd },
|
|
44
46
|
...job.timeoutMs ? [{ label: 'timeout', value: `${job.timeoutMs}ms` }] : [],
|
|
45
47
|
...job.taskId ? [{ label: 'task', value: `${job.taskId} · source generation: ${job.taskGeneration ?? 'unavailable (legacy link expired)'}` }] : [],
|
|
46
48
|
{ label: 'state', value: job.state, tone: stateLine(job.state).tone },
|
|
49
|
+
...job.elapsedMs !== undefined ? [{ label: 'runtime', value: elapsedText(job.elapsedMs) }] : [],
|
|
50
|
+
...job.exitCode !== null || job.signal ? [{ label: 'exit', value: String(exit) }] : [],
|
|
51
|
+
...job.stopReason ? [{ label: 'stop reason', value: job.stopReason }] : [],
|
|
52
|
+
...job.completionReason ? [{ label: 'completion', value: job.completionReason }] : [],
|
|
47
53
|
{ label: 'cleanup', value: job.cleanup.state, tone: cleanupTone(job.cleanup.state) },
|
|
48
54
|
...job.cleanup.error ? [{ label: 'cleanup error', value: job.cleanup.error, tone: 'warning' as const }] : [],
|
|
55
|
+
...job.monitor ? [{ label: 'monitor', value: `${job.monitor.config.strategy ?? 'stream'} · events ${job.monitor.events} (${job.monitor.notifiedEvents} notified)` }] : [],
|
|
56
|
+
...job.handsFree ? [{ label: 'supervision', value: `${job.handsFree.config.mode} · updates ${job.handsFree.updates} · output ${job.handsFree.totalCharsSent}/${job.handsFree.config.maxTotalChars} chars` }] : [],
|
|
57
|
+
...job.creator ? [{ label: 'created by', value: `${job.creator.agentId ?? job.creator.workflowId} ${job.creator.runId}` }] : [],
|
|
49
58
|
...job.error ? [{ label: 'error', value: job.error, tone: 'error' as const }] : [],
|
|
50
59
|
];
|
|
51
60
|
}
|
|
@@ -71,8 +80,7 @@ export const getRenderers = toolRenderers<JobArgs, JobDetails & { live: boolean
|
|
|
71
80
|
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job', summary: args.id }),
|
|
72
81
|
collapsed: ({ job }) => ({ ...stateLine(job.state), title: job.id, summary: name(job),
|
|
73
82
|
meta: [{ text: job.state, tone: stateLine(job.state).tone! }, ...job.error ? [{ text: 'error', tone: 'error' as const }] : []] }),
|
|
74
|
-
expanded: ({ job, live }) => [...jobFields(job), { label: 'live', value: String(live) },
|
|
75
|
-
{ code: JSON.stringify(job, null, 2), language: 'json', label: 'details' }],
|
|
83
|
+
expanded: ({ job, live }) => [...jobFields(job), { label: 'live', value: String(live) }],
|
|
76
84
|
});
|
|
77
85
|
export const readRenderers = toolRenderers<ReadArgs, ReadDetails>({
|
|
78
86
|
call: args => ({ icon: '⟳', tone: 'accent', title: 'Job read', summary: args.id, meta: args.stream ? [args.stream] : [] }),
|
|
@@ -99,5 +107,5 @@ export const stopRenderers = toolRenderers<JobArgs, StopOutcome & JobDetails>({
|
|
|
99
107
|
summary: data.requested ? data.state : 'already settled',
|
|
100
108
|
meta: [{ text: `cleanup ${data.cleanup === 'managed_scope_confirmed' ? 'confirmed' : data.cleanup}`, tone: cleanupTone(data.cleanup) }] }),
|
|
101
109
|
expanded: data => [...jobFields(data.job), { label: 'requested', value: String(data.requested) },
|
|
102
|
-
{
|
|
110
|
+
{ label: 'affected', value: data.affected.map(item => `${item.id}: ${item.state}${item.cleanup ? ` (cleanup ${item.cleanup})` : ''}`).join('\n') }],
|
|
103
111
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AgentBeforeSettleEvent, BoundaryResult, ExtensionAPI, ExtensionContext, TurnEndEvent } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import type { SessionBinding, Binding } from '../binding.ts';
|
|
3
|
-
import { projectReplay, replayPayload, resourceMismatch, sha256, type
|
|
3
|
+
import { projectReplay, replayPayload, resourceMismatch, sha256, type ReplayReferences } from './payload.ts';
|
|
4
4
|
|
|
5
5
|
export const RECOVERY_ENTRY = 'pi-suite:responses-isolation';
|
|
6
6
|
type Isolation = { version: 2; scope: string; ids: string[]; ciphers: string[] };
|
|
@@ -8,19 +8,18 @@ type IsolationSets = { ids: Set<string>; ciphers: Set<string> };
|
|
|
8
8
|
type Request = ReplayReferences & { generation: number; binding: Binding; scope: string; leaf: string | null; signal?: AbortSignal };
|
|
9
9
|
type Failure = { request: Request; entryId: string; error: string };
|
|
10
10
|
|
|
11
|
-
/** Per-session request projection only; retries/backoff and their budgets belong to Pi.
|
|
11
|
+
/** Per-session request projection only; native retries/backoff and their budgets belong to Pi.
|
|
12
12
|
* The append-only branch record stores IDs, cipher hashes and a hashed endpoint scope, never payload/auth.
|
|
13
13
|
*/
|
|
14
14
|
export class ResponsesRecovery {
|
|
15
15
|
private isolated = new Map<string, IsolationSets>();
|
|
16
16
|
private request?: Request;
|
|
17
17
|
private failure?: Failure;
|
|
18
|
-
private recovering?: { scope: string; used: Set<RepairKind> };
|
|
19
18
|
private generation = 0;
|
|
20
19
|
constructor(private binding: SessionBinding, private enabled: boolean) {}
|
|
21
20
|
|
|
22
21
|
reset(ctx?: ExtensionContext): void {
|
|
23
|
-
this.
|
|
22
|
+
this.settled();
|
|
24
23
|
this.isolated.clear(); this.generation++;
|
|
25
24
|
if (!this.enabled || !ctx) return;
|
|
26
25
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
@@ -46,15 +45,13 @@ export class ResponsesRecovery {
|
|
|
46
45
|
}
|
|
47
46
|
|
|
48
47
|
beforeRequest(payload: unknown, ctx: ExtensionContext): unknown {
|
|
49
|
-
// A new final payload invalidates the last attempt,
|
|
50
|
-
|
|
51
|
-
this.request = undefined; this.failure = undefined;
|
|
48
|
+
// A new final payload invalidates the last attempt, not the branch isolation.
|
|
49
|
+
this.settled();
|
|
52
50
|
const active = this.binding.current, model = ctx.model;
|
|
53
51
|
if (!this.enabled || !active || active.ctx.sessionManager !== ctx.sessionManager || model?.api !== 'openai-responses') return;
|
|
54
52
|
const wire = replayPayload(payload, model.id);
|
|
55
53
|
if (!wire) return;
|
|
56
54
|
const scope = sha256(JSON.stringify([model.provider, model.api, model.id, model.baseUrl]));
|
|
57
|
-
if (this.recovering && this.recovering.scope !== scope) this.recovering = undefined;
|
|
58
55
|
const { projected, ids, ciphers } = projectReplay(wire, this.isolated.get(scope));
|
|
59
56
|
// Raw ciphertext is needed for fragment matching, but lives only in the in-flight request state.
|
|
60
57
|
this.request = { generation: ++this.generation, binding: active, scope,
|
|
@@ -76,35 +73,34 @@ export class ResponsesRecovery {
|
|
|
76
73
|
const leafIndex = request.leaf === null ? -1 : branch.findIndex(entry => entry.id === request.leaf);
|
|
77
74
|
if (sourceIndex < 0 || request.leaf !== null && leafIndex < 0 || sourceIndex <= leafIndex ||
|
|
78
75
|
branch.slice(leafIndex + 1, sourceIndex).some(entry => entry.type === 'message' && entry.message.role === 'assistant')) return;
|
|
79
|
-
if (message.stopReason === 'error') {
|
|
80
|
-
|
|
81
|
-
}
|
|
76
|
+
if (message.stopReason === 'error' && !message.content.length && message.errorMessage) {
|
|
77
|
+
this.failure = { request, entryId: source.id, error: message.errorMessage };
|
|
78
|
+
}
|
|
82
79
|
}
|
|
83
80
|
|
|
84
81
|
beforeSettle(event: AgentBeforeSettleEvent): BoundaryResult | undefined {
|
|
85
82
|
const failure = this.failure;
|
|
86
83
|
if (!failure || event.outcome !== 'error' || failure.request.signal?.aborted || !this.binding.isCurrent(failure.request.binding) ||
|
|
87
84
|
failure.request.generation !== this.request?.generation) return;
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
// one-use slots: a resource repair can expose a cipher error on the very next request.
|
|
91
|
-
// Only a successful turn permits a later new phase at this scope.
|
|
92
|
-
if (!kind || this.recovering?.used.has(kind)) return;
|
|
85
|
+
const match = resourceMismatch(failure.error, failure.request);
|
|
86
|
+
if (!match) return;
|
|
93
87
|
const source = event.context.contextEntries.find(entry => entry.sourceEntry.id === failure.entryId);
|
|
94
88
|
if (!source) return; // Compaction/another projection removed the source from this boundary.
|
|
95
89
|
const visible = source.messages.length;
|
|
96
90
|
if (!visible && event.continue) return; // A preceding extension already owns this failure.
|
|
97
91
|
const { scope, ids, ciphers } = failure.request;
|
|
98
92
|
const known = this.isolated.get(scope);
|
|
99
|
-
//
|
|
100
|
-
//
|
|
93
|
+
// If the gateway named no target, try all references of that kind rather
|
|
94
|
+
// than guessing which one is stale. A cipher failure alone implicates no IDs.
|
|
95
|
+
const targetIds = match.kind === 'id' ? (match.ids.length ? match.ids : ids) : [];
|
|
96
|
+
const targetCiphers = match.kind === 'cipher' ? (match.ciphers.length ? match.ciphers : ciphers) : [];
|
|
101
97
|
const record: Isolation = { version: 2, scope,
|
|
102
|
-
ids: [...new Set(
|
|
103
|
-
ciphers:
|
|
98
|
+
ids: [...new Set(targetIds)].filter(id => !known?.ids.has(id)),
|
|
99
|
+
ciphers: [...new Set(targetCiphers.map(sha256))].filter(hash => !known?.ciphers.has(hash)),
|
|
104
100
|
};
|
|
101
|
+
// Allow consecutive repairs of the same kind only if each changes the next
|
|
102
|
+
// replay. A repeat after full isolation stops unless new references appeared.
|
|
105
103
|
if (!record.ids.length && !record.ciphers.length) return;
|
|
106
|
-
this.recovering ??= { scope, used: new Set() };
|
|
107
|
-
this.recovering.used.add(kind);
|
|
108
104
|
this.addIsolation(record);
|
|
109
105
|
return { continue: true, entries: [...event.entries,
|
|
110
106
|
{ type: 'custom', customType: RECOVERY_ENTRY, data: record },
|
|
@@ -112,7 +108,7 @@ export class ResponsesRecovery {
|
|
|
112
108
|
] };
|
|
113
109
|
}
|
|
114
110
|
|
|
115
|
-
settled(): void { this.request = undefined; this.failure = undefined;
|
|
111
|
+
settled(): void { this.request = undefined; this.failure = undefined; }
|
|
116
112
|
}
|
|
117
113
|
|
|
118
114
|
/** The caller owns ordering with Goal and notifications at the actionable/final boundaries. */
|
|
@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto';
|
|
|
3
3
|
type Item = Record<string, unknown>;
|
|
4
4
|
export type ReplayPayload = Item & { input: Item[] };
|
|
5
5
|
export type ReplayReferences = { ids: string[]; ciphers: string[] };
|
|
6
|
-
|
|
6
|
+
type RepairMatch = { kind: 'id'; ids: string[] } | { kind: 'cipher'; ciphers: string[] };
|
|
7
7
|
export const sha256 = (value: string): string => createHash('sha256').update(value).digest('hex');
|
|
8
8
|
const object = (value: unknown): value is Item => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
9
|
const upstreamId = (item: Item): string | undefined => typeof item.id === 'string' &&
|
|
@@ -79,23 +79,26 @@ export function projectReplay(payload: ReplayPayload, isolated?: { ids: Readonly
|
|
|
79
79
|
/** SDK errors are normalized even when an HTTP status callback is unavailable.
|
|
80
80
|
* Require a specific ownership/dependency or encrypted reasoning failure, not a generic HTTP 400 or crypto error.
|
|
81
81
|
*/
|
|
82
|
-
export function resourceMismatch(error: string, { ids, ciphers }: ReplayReferences):
|
|
82
|
+
export function resourceMismatch(error: string, { ids, ciphers }: ReplayReferences): RepairMatch | undefined {
|
|
83
83
|
const text = error.toLowerCase();
|
|
84
84
|
if (/\b(?:401|403|429|5\d\d)\b|rate.?limit|quota|billing|context.{0,20}(?:length|window)|maximum context/.test(text)) return;
|
|
85
85
|
if (/\bencrypted\b[^\r\n]*?\b(?:cannot|could not) be (?:verified|decrypted)\b/.test(text)) {
|
|
86
86
|
if (!ciphers.length) return;
|
|
87
87
|
// Gateways can identify a ciphertext without naming its item. Compare any
|
|
88
88
|
// reported fragment case-sensitively; a mismatch invalidates the correlation.
|
|
89
|
+
const matched = new Set<string>();
|
|
89
90
|
for (const [, prefix, suffix] of error.matchAll(/(?<![A-Za-z0-9_-])([A-Za-z0-9_-]{4,})\.{3}([A-Za-z0-9_-]{4,})/g)) {
|
|
90
|
-
|
|
91
|
+
const candidates = ciphers.filter(cipher => cipher.startsWith(prefix) && cipher.endsWith(suffix));
|
|
92
|
+
if (!candidates.length) return;
|
|
93
|
+
for (const cipher of candidates) matched.add(cipher);
|
|
91
94
|
}
|
|
92
|
-
return 'cipher';
|
|
95
|
+
return { kind: 'cipher', ciphers: [...matched] };
|
|
93
96
|
}
|
|
94
|
-
const
|
|
97
|
+
const matchedIds = ids.filter(id => error.includes(id));
|
|
95
98
|
const resource = /(?:different|another|across|cross)[ -](?:openai[ -])?(?:resource|organization|project)|(?:resource|organization|project).{0,50}(?:mismatch|does not match|not belong)/.test(text);
|
|
96
99
|
// Gateways may omit the item ID and qualify/redact the resource name. Recognize
|
|
97
100
|
// the explicit creation-origin sentence, not arbitrary words between "different" and "resource".
|
|
98
101
|
const createdElsewhere = /\bitem was created (?:under|in) (?:a different|another) [^.!?\r\n]{0,80}\b(?:resource|organization|project)\b/.test(text);
|
|
99
|
-
const ownership =
|
|
100
|
-
if (resource || createdElsewhere || ownership) return 'id';
|
|
102
|
+
const ownership = matchedIds.length > 0 && /not found|does not exist|belongs to|was created in|provided without.{0,80}required|not owned by/.test(text);
|
|
103
|
+
if (resource || createdElsewhere || ownership) return { kind: 'id', ids: matchedIds };
|
|
101
104
|
}
|
package/src/tasks/render.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { toolRenderers, type ToolLine } from '../ui/tool-render.ts';
|
|
1
|
+
import { toolRenderers, type ToolExpandedRow, type ToolLine } from '../ui/tool-render.ts';
|
|
2
|
+
import type { StructuredDetails } from '../ui/structured-details.ts';
|
|
2
3
|
import { taskIcon, taskTone, taskHeading, receiptAction, receiptDisplay } from './presentation.ts';
|
|
3
4
|
import type { EditResult, TaskView } from './types.ts';
|
|
4
5
|
|
|
@@ -20,11 +21,19 @@ export const listRenderers = toolRenderers<{ state?: string; groupId?: string },
|
|
|
20
21
|
...nextCursor ? [{ label: 'more', value: 'next page available', tone: 'warning' as const }] : [], ...tasks.length ? [] : ['No tasks'],
|
|
21
22
|
],
|
|
22
23
|
});
|
|
23
|
-
export const getRenderers = toolRenderers<{ id: string }, { task: TaskView; generation: string }>({
|
|
24
|
+
export const getRenderers = toolRenderers<{ id: string }, { task: TaskView; generation: string; view?: StructuredDetails }>({
|
|
24
25
|
call: () => ({ icon: '⟳', tone: 'accent', title: 'Task' }),
|
|
25
26
|
collapsed: ({ task }) => ({ ...line(task), meta: task.progress ? [`${task.progress.done}/${task.progress.total}`] : [] }),
|
|
26
|
-
|
|
27
|
-
|
|
27
|
+
// Saved tool results without detail rows still have the original receipt text.
|
|
28
|
+
expanded: ({ generation, view }, _args, text) => view ? [{ label: 'generation', value: generation },
|
|
29
|
+
...view.rows.flatMap<ToolExpandedRow>(row => {
|
|
30
|
+
if (typeof row === 'string') return [row];
|
|
31
|
+
if (!row || !('length' in row)) return [];
|
|
32
|
+
const [head, ...rest] = row;
|
|
33
|
+
return head?.role === 'label'
|
|
34
|
+
? [{ label: head.text.trimEnd().replace(/:$/, ''), value: rest.map(part => part.text).join('') }]
|
|
35
|
+
: [row.map(part => part.text).join('')];
|
|
36
|
+
})] : [text],
|
|
28
37
|
});
|
|
29
38
|
export const editRenderers = toolRenderers<unknown, EditResult>({
|
|
30
39
|
call: () => ({ icon: '⟳', tone: 'accent', title: 'Updating tasks…' }),
|
|
@@ -47,7 +56,7 @@ export const editRenderers = toolRenderers<unknown, EditResult>({
|
|
|
47
56
|
...data.changes.map(change => ({ ...line({ ...change, status: change.after ?? change.before ?? 'todo' }),
|
|
48
57
|
summary: receiptDisplay(change).slice(receiptDisplay(change).indexOf(' · ') + 3) })),
|
|
49
58
|
...data.derived.map(change => ({ ...line(change), summary: change.status === 'blocked' ? 'blocked' : 'dependencies cleared' })),
|
|
50
|
-
...data.changes.
|
|
59
|
+
...data.changes.flatMap(change => Object.entries(change.fields ?? {}).map(([key, value]) => ({ label: `fields ${change.id} ${key}`, value: String(value) }))),
|
|
51
60
|
...data.progress.map(group => ({ label: `group ${group.id}`, value: `${group.done}/${group.total} ${group.status}`, tone: taskTone(group.status) })),
|
|
52
61
|
...data.warnings.map(warning => ({ label: 'warning', value: warning, tone: 'warning' as const })),
|
|
53
62
|
],
|
package/src/tasks/tools.ts
CHANGED
|
@@ -4,7 +4,8 @@ import { registerBoundTool, checkedArguments, LIST_LIMITS, paginate, textResult
|
|
|
4
4
|
import { boundedText } from '../runtime/read.ts';
|
|
5
5
|
import type { TasksModule } from './index.ts';
|
|
6
6
|
import { taskId, taskScope, groupId, generationSchema, type TaskScope, type TaskView } from './types.ts';
|
|
7
|
-
import {
|
|
7
|
+
import { plainDetailLines } from '../ui/structured-details.ts';
|
|
8
|
+
import { taskDetailsView, taskLabel, type TaskFilter } from './query.ts';
|
|
8
9
|
import { taskViews } from './model.ts';
|
|
9
10
|
import { editSchema, editArguments, editChanges } from './schema.ts';
|
|
10
11
|
import { requireGeneration } from './types.ts';
|
|
@@ -51,7 +52,9 @@ export function registerTaskTools(pi: ExtensionAPI, tasks: TasksModule): void {
|
|
|
51
52
|
async execute(_id, params, _signal, _update, ctx) {
|
|
52
53
|
const scope = (params as { scope?: TaskScope }).scope;
|
|
53
54
|
const { task, views } = await tasks.get(ctx, params.id, params.generation, scope);
|
|
54
|
-
|
|
55
|
+
// Persist the selected task's detail rows, not the Map of the entire list.
|
|
56
|
+
const view = taskDetailsView(task, views);
|
|
57
|
+
return textResult([`generation: ${params.generation}`, scope === 'assigned' ? `assigned task ${params.id} (parent list)` : undefined, ...plainDetailLines(view)], { task, generation: params.generation, view });
|
|
55
58
|
},
|
|
56
59
|
...getRenderers,
|
|
57
60
|
}, 'initial');
|
package/src/ui/details.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { commandFrame } from './frame.ts';
|
|
|
10
10
|
import { openReading, readingRows, readingText, readingWindow } from './reading.ts';
|
|
11
11
|
import { sanitizeText } from '../runtime/text.ts';
|
|
12
12
|
import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
|
|
13
|
-
import {
|
|
13
|
+
import { plainDetailLines, readingDetailsContent, type StructuredDetails } from './structured-details.ts';
|
|
14
14
|
|
|
15
15
|
export interface DetailOptions {
|
|
16
16
|
title?: boolean;
|
|
@@ -104,8 +104,20 @@ export async function showDetails(ctx: ExtensionContext, dock: Dock, title: stri
|
|
|
104
104
|
}
|
|
105
105
|
dock.setDetail(true);
|
|
106
106
|
try {
|
|
107
|
-
await openReading<void>(ctx, (tui, theme, keys, done) =>
|
|
108
|
-
typeof content !== 'string' ?
|
|
109
|
-
|
|
107
|
+
await openReading<void>(ctx, (tui, theme, keys, done) => {
|
|
108
|
+
const {body, output} = typeof content !== 'string' ? readingDetailsContent(content, theme) : {
|
|
109
|
+
body: format === 'text' ? new Text(sanitizeText(content), 0, 0) : new Markdown(content, 0, 0, getMarkdownTheme()),
|
|
110
|
+
};
|
|
111
|
+
const view = new DetailsView(tui, () => title, body, done, [], undefined, theme, {navigation, keys});
|
|
112
|
+
if (output) view.actions.push({key: 'e',
|
|
113
|
+
get label() { return output.expanded ? 'Collapse output' : 'Expand output'; },
|
|
114
|
+
run: () => {
|
|
115
|
+
// End follows the document tail. Stay at the summary instead of jumping to the end of the expanded result.
|
|
116
|
+
view.reader.pause();
|
|
117
|
+
output.toggle();
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
return view;
|
|
121
|
+
});
|
|
110
122
|
} finally { dock.setDetail(false); }
|
|
111
123
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { Text } from '@earendil-works/pi-tui';
|
|
1
|
+
import { getMarkdownTheme, type Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Container, Markdown, Text, truncateToWidth, type Component } from '@earendil-works/pi-tui';
|
|
3
3
|
import { detailPartText, divider, heading, type DetailPart } from './browser-chrome.ts';
|
|
4
4
|
import { sanitizeText } from '../runtime/text.ts';
|
|
5
5
|
|
|
6
6
|
/** A section names the block below it (metadata, input, output) so long free text is never
|
|
7
7
|
* mistaken for a field value. It always starts a new group. */
|
|
8
8
|
export interface DetailSection { section: string }
|
|
9
|
-
export
|
|
9
|
+
export interface DetailOutput { output: string; markdown?: boolean }
|
|
10
|
+
export type DetailRow = string | readonly DetailPart[] | DetailSection | DetailOutput;
|
|
10
11
|
/** null marks a UI group break; undefined omits an optional row. */
|
|
11
12
|
export interface StructuredDetails { rows: readonly (DetailRow | null | undefined)[] }
|
|
12
13
|
|
|
@@ -15,27 +16,72 @@ export const statePart = (text: string | boolean, state = String(text)): DetailP
|
|
|
15
16
|
export const field = (label: string, value: DetailPart | string | number | boolean, ...suffix: DetailPart[]): DetailRow =>
|
|
16
17
|
[part(`${label} `, 'label'), typeof value === 'object' ? value : part(value), ...suffix];
|
|
17
18
|
export const section = (title: string): DetailSection => ({ section: title });
|
|
19
|
+
export const outputRow = (output: string, options?: Pick<DetailOutput, 'markdown'>): DetailOutput => ({ output, ...options });
|
|
18
20
|
const isSection = (row: DetailRow): row is DetailSection => typeof row === 'object' && 'section' in row;
|
|
21
|
+
const isOutput = (row: DetailRow): row is DetailOutput => typeof row === 'object' && 'output' in row;
|
|
19
22
|
const sectionText = (title: string, theme?: Theme) => `${divider('──', theme)} ${heading(sanitizeText(title), theme)} ${divider('──', theme)}`;
|
|
20
23
|
|
|
21
|
-
/**
|
|
24
|
+
/** Non-TUI receipts keep the original text: expansion is local to the interactive reader. */
|
|
22
25
|
export function plainDetailLines({ rows }: StructuredDetails): string[] {
|
|
23
|
-
return rows.flatMap(row => row == null ? [] : [typeof row === 'string' ? row : isSection(row) ? `── ${row.section} ──`
|
|
26
|
+
return rows.flatMap(row => row == null ? [] : [typeof row === 'string' ? row : isSection(row) ? `── ${row.section} ──`
|
|
27
|
+
: isOutput(row) ? row.output : row.map(({text}) => text).join('')]);
|
|
24
28
|
}
|
|
25
29
|
|
|
26
|
-
|
|
27
|
-
const lines: string[] = [];
|
|
30
|
+
function detailLines({ rows }: StructuredDetails, theme?: Theme): (string | DetailOutput)[] {
|
|
31
|
+
const lines: (string | DetailOutput)[] = [];
|
|
28
32
|
let gap = false;
|
|
29
33
|
for (const row of rows) {
|
|
30
34
|
if (row === undefined) continue;
|
|
31
35
|
if (row === null) { gap = true; continue; }
|
|
32
|
-
const line = isSection(row) ? sectionText(row.section, theme)
|
|
33
|
-
: (typeof row === 'string' ? [part(row)] : row).map(value => detailPartText(value, theme)).join('');
|
|
34
36
|
if ((gap || isSection(row)) && lines.length) lines.push('');
|
|
35
|
-
lines.push(
|
|
37
|
+
lines.push(isOutput(row) ? row : isSection(row) ? sectionText(row.section, theme)
|
|
38
|
+
: (typeof row === 'string' ? [part(row)] : row).map(value => detailPartText(value, theme)).join(''));
|
|
36
39
|
gap = false;
|
|
37
40
|
}
|
|
38
|
-
return lines
|
|
41
|
+
return lines;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const joinDetailLines = (lines: (string | DetailOutput)[]): string =>
|
|
45
|
+
lines.map(line => typeof line === 'string' ? line : sanitizeText(line.output)).join('\n');
|
|
46
|
+
|
|
47
|
+
export function detailsText(details: StructuredDetails, theme?: Theme): string {
|
|
48
|
+
return joinDetailLines(detailLines(details, theme));
|
|
39
49
|
}
|
|
40
50
|
|
|
41
51
|
export const detailsContent = (details: StructuredDetails, theme?: Theme): Text => new Text(detailsText(details, theme), 0, 0);
|
|
52
|
+
|
|
53
|
+
/** Output owns only its display state, not ToolRenderer's tool invocation and result templates. */
|
|
54
|
+
class DetailOutputView implements Component {
|
|
55
|
+
expanded = false;
|
|
56
|
+
private readonly summary: string;
|
|
57
|
+
private body?: Component;
|
|
58
|
+
|
|
59
|
+
constructor(private row: DetailOutput) {
|
|
60
|
+
const count = row.output ? row.output.split('\n').length : 0;
|
|
61
|
+
this.summary = `Output: ${count} ${count === 1 ? 'line' : 'lines'} · e expand`;
|
|
62
|
+
}
|
|
63
|
+
toggle(): void { this.expanded = !this.expanded; }
|
|
64
|
+
invalidate(): void { this.body?.invalidate(); }
|
|
65
|
+
render(width: number): readonly string[] {
|
|
66
|
+
if (!this.expanded) return [truncateToWidth(this.summary, width)];
|
|
67
|
+
// Defer Markdown construction until the user opens the result; keep its native render cache.
|
|
68
|
+
if (!this.body) {
|
|
69
|
+
const text = sanitizeText(this.row.output);
|
|
70
|
+
this.body = this.row.markdown ? new Markdown(text, 0, 0, getMarkdownTheme()) : new Text(text, 0, 0);
|
|
71
|
+
}
|
|
72
|
+
return this.body.render(width);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Only the dedicated detail reader binds a toggle; list previews still use static detailsContent. */
|
|
77
|
+
export function readingDetailsContent(details: StructuredDetails, theme?: Theme): { body: Component; output?: DetailOutputView } {
|
|
78
|
+
const lines = detailLines(details, theme);
|
|
79
|
+
const index = lines.findIndex(line => typeof line !== 'string');
|
|
80
|
+
const row = lines[index];
|
|
81
|
+
if (row === undefined || typeof row === 'string') return { body: new Text(joinDetailLines(lines), 0, 0) };
|
|
82
|
+
const output = new DetailOutputView(row), body = new Container();
|
|
83
|
+
body.addChild(new Text(joinDetailLines(lines.slice(0, index)), 0, 0));
|
|
84
|
+
body.addChild(output);
|
|
85
|
+
if (index + 1 < lines.length) body.addChild(new Text(joinDetailLines(lines.slice(index + 1)), 0, 0));
|
|
86
|
+
return {body, output};
|
|
87
|
+
}
|