@cobia/pi-onward 0.4.0 → 0.4.1

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 CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  </div>
8
8
 
9
- pi-onward 只处理两类失败:Pi 明确以错误结束,或者正常结束但没有文字、工具调用。规则先匹配失败,再根据连续失败次数选择恢复阶段。每个阶段引用一个具名动作;内置重发、发消息、停止、调用扩展命令,以及其他插件提供的结构化能力,都走同一套动作接口。
9
+ pi-onward 只处理两类失败:Pi 明确以错误结束,或者正常结束但没有文字、工具调用。规则先匹配失败,再根据连续失败次数选择恢复阶段。每个阶段引用一个具名动作;内置发消息、调用扩展命令、停止,以及其他插件提供的结构化能力,都走同一套动作接口。
10
10
 
11
11
  ## 安装
12
12
 
@@ -37,12 +37,15 @@ pi-onward 本身没有默认规则。复制包里的 [`example.json`](example.js
37
37
  {
38
38
  "minFailures": 1,
39
39
  "delay": "3s",
40
- "action": { "use": "onward.resend" }
40
+ "action": {
41
+ "use": "pi.message",
42
+ "with": { "prompt": "{taskPrompt}" }
43
+ }
41
44
  },
42
45
  {
43
46
  "minFailures": 3,
44
47
  "action": {
45
- "use": "onward.command",
48
+ "use": "pi.command",
46
49
  "with": {
47
50
  "name": "example-command",
48
51
  "args": "-- 继续执行当前任务"
@@ -55,9 +58,9 @@ pi-onward 本身没有默认规则。复制包里的 [`example.json`](example.js
55
58
  }
56
59
  ```
57
60
 
58
- 这条规则的行为是:第 1、2 次失败重发,第 3 次失败后在当前轮次落定,再调用扩展命令。`example-command` 是占位名称,需要替换成实际已加载的命令,`args` 按目标命令的参数格式填写。第一阶段的 `minFailures` 必须是 1,之后严格递增。旧字段 `fromFailure` 已移除,需要改为 `minFailures`。
61
+ 这条规则的行为是:第 1、2 次失败发送任务提示词续跑,第 3 次失败后在当前轮次落定,再调用扩展命令。`example-command` 是占位名称,需要替换成实际已加载的命令,`args` 按目标命令的参数格式填写。第一阶段的 `minFailures` 必须是 1,之后严格递增。
59
62
 
60
- `onward.command` 确认目标是已加载的扩展命令,再通过 Pi 分派。`args` 原样传给命令,不经过 shell、不替换 onward 模板,也不需要模型来执行。`/model` 等 Pi 内置交互命令不属于扩展命令,不支持这个入口。
63
+ `pi.command` 确认目标是已加载的扩展命令,再通过 Pi 分派。`args` 原样传给命令,不经过 shell、不替换 onward 模板,也不需要模型来执行。`/model` 等 Pi 内置交互命令不属于扩展命令,不支持这个入口。
61
64
 
62
65
  结果只能保证“已分派”,不能保证目标插件的业务操作已成功,也不能强制取消已经进入命令处理器的操作。需要结构化结果或恢复链传递时,可以加载提供动作的独立桥接扩展,或让插件选择实现动作协议:
63
66
 
@@ -75,25 +78,30 @@ pi-onward 本身没有默认规则。复制包里的 [`example.json`](example.js
75
78
 
76
79
  ## 内置动作
77
80
 
81
+ `pi.message` 和 `pi.command` 由 onward 内置的 Pi 适配模块提供,加载 onward 后自动注册,无需另外安装。`pi` 表示对接 Pi 的动作命名空间,并非 Pi 官方 API。
82
+
78
83
  | 动作 | 阶段 | 作用 |
79
84
  | --- | --- | --- |
80
- | `onward.resend` | `boundary` | 从模型上下文省略失败回复,重发请求 |
81
- | `onward.message` | `boundary` | 追加一条自定义消息并继续;`prompt` 支持 `{failures}`、`{rule}`、`{error}`、`{taskPrompt}` |
85
+ | `pi.message` | `boundary` | 追加一条自定义消息并继续;`prompt` 支持 `{failures}`、`{rule}`、`{error}`、`{taskPrompt}` |
86
+ | `pi.command` | `settled` | 在当前轮次落定后调用已加载的扩展命令 |
82
87
  | `onward.stop` | `boundary` | 停止当前恢复过程 |
83
- | `onward.command` | `settled` | 在当前轮次落定后调用已加载的扩展命令 |
88
+
89
+ `pi.message` 在 `agent_before_settle` 提交消息和继续运行的提议;`pi.command` 在所有 `agent_settled` 观察者完成后,通过 `pi.sendUserMessage()` 的命令分派机制调用目标。目标扩展使用 `pi.registerCommand()` 注册命令,不需要实现 onward 动作协议。
84
90
 
85
91
  `prompt` 默认是 `继续`,所有变量都使用 `{变量名}`,可以与正文拼接。`{taskPrompt}` 替换为本轮任务的提示词文本,例如:
86
92
 
87
93
  ```json
88
94
  {
89
- "use": "onward.message",
95
+ "use": "pi.message",
90
96
  "with": { "prompt": "请重新尝试:\n{taskPrompt}" }
91
97
  }
92
98
  ```
93
99
 
94
- 上次输入为 `检查并修复登录接口` 时,会追加 `请重新尝试:` 换行后接该输入。`"prompt": "{taskPrompt}"` 只发送原提示词,`"prompt": "继续{taskPrompt}"` 则在前面加上“继续”。这会追加新消息;独立的 `onward.resend` 仍表示省略失败回复后静默重发请求。
100
+ 上次输入为 `检查并修复登录接口` 时,会追加 `请重新尝试:` 换行后接该输入。重发任务提示词使用 `pi.message`:`"prompt": "{taskPrompt}"` 发送原提示词,`"prompt": "继续{taskPrompt}"` 则在前面加上“继续”。两种写法都会追加一条新消息。
101
+
102
+ `{taskPrompt}` 使用真正进入会话的用户消息文本,包含输入扩展改写、Pi 技能及提示词模板展开后的结果。人工或 RPC 消息被接收后才更新任务来源和恢复计数;被扩展拦截、尚未消费或已取消的输入不会成为新任务。自动续跑保留原任务;新会话首次由扩展发起任务时,以该消息为任务来源。
95
103
 
96
- 人工或 RPC 新输入会更新 `{taskPrompt}` 的来源,记录的是输入事件中的文本(Pi 技能和提示词模板展开前)。自动续跑不覆盖来源;新会话首次由扩展发起任务时,以该输入为来源。恢复会话或切换分支时,从当前分支最近的用户消息中提取文本,跳过 onward 的自定义续跑消息。仅复用文字,不复制图片附件或整个请求上下文。没有可复用的任务文本时,使用 `{taskPrompt}` 的动作会明确失败并停止本次恢复。
104
+ onward 随已接收的用户消息保存来源记录,记录不包含提示词正文,也不进入模型上下文。重载、恢复会话或切换分支时,根据当前分支的来源记录重建任务,不把自动续跑消息当成新任务。仅复用文字,不复制图片附件或整个请求上下文。缺少任务文本、来源记录或无法确定排队消息来源时,使用 `{taskPrompt}` 的动作会明确失败并停止本次恢复。
97
105
 
98
106
  模板只替换一次:原提示词或错误信息中包含的 `{error}`、`{taskPrompt}` 等文字保持原样。未知变量保持原文。
99
107
 
@@ -140,7 +148,7 @@ export default function (pi: ExtensionAPI) {
140
148
 
141
149
  动作有两种执行阶段:
142
150
 
143
- - `boundary`:在 `agent_before_settle` 中返回下一轮提议,适合 `resend` 和 `message`。
151
+ - `boundary`:在 `agent_before_settle` 中返回下一轮提议,例如 `pi.message`。
144
152
  - `settled`:等 Pi 完全落定后执行,适合命令、会话切换、重启和外部副作用。
145
153
 
146
154
  动作结果分为继续、完成、已分派、已接管、停止、失败、取消和未知。动作超时、抛出异常或返回非法结果时,结果标记为未知,不会自动重放可能已经产生副作用的动作。
@@ -153,7 +161,7 @@ export default function (pi: ExtensionAPI) {
153
161
  - `maxHandoffs`:恢复链最多跨 session 接管的次数,默认 3;0 表示禁止接管。
154
162
  - `actionTimeout`:单次动作执行时限,默认 30 秒。等待 `delay` 不计入动作时限。
155
163
 
156
- 正常模型回复一次(包括工具轮)会结束恢复过程。人工新任务、Esc、关闭、重载、切换分支和配置修改会取消未执行动作;其中 Esc 保留本次失败的诊断状态。扩展自动发送的续跑消息不会清空当前恢复过程。这里的一次失败是 `agent_before_settle` 看到的最终结果,不包含 Pi 内建重试期间的每个 HTTP 请求。
164
+ 正常模型回复一次(包括工具轮)会结束恢复过程。已接收的人工新任务、Esc、关闭、重载、切换分支和配置修改会取消未执行动作;其中 Esc 保留本次失败的诊断状态。扩展自动发送的续跑消息不会清空当前恢复过程。这里的一次失败是 `agent_before_settle` 看到的最终结果,不包含 Pi 内建重试期间的每个 HTTP 请求。
157
165
 
158
166
  带 `handoff: true` 的动作在调用前预留一次接管预算。明确失败、取消或只完成预览时退回预算;超时或异常结果未知时保留。动作提供者必须通过自己的持久交接保存恢复链,并在目标会话启动时恢复,详见[动作协议](docs/actions.md)。
159
167
 
@@ -234,4 +242,4 @@ npm run check:extension
234
242
 
235
243
  扩展动作属于进程内协议,插件的 npm 包仍由 Pi 安装和加载。只加载你信任的扩展。
236
244
 
237
- 测试使用隔离配置和本地注册的测试命令、动作,不依赖其他扩展,不读取真实凭据,也不调用外部模型。
245
+ 测试使用隔离配置、真实 Pi 输入链和本地模型响应,不依赖其他扩展,不读取真实凭据,也不调用外部模型。
package/docs/actions.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 动作提供者协议
2
2
 
3
- 普通插件命令使用 `onward.command`,目标插件只需已在 Pi 中注册命令,不需要实现本文的协议。本文用于独立桥接扩展或插件主动提供结构化能力。
3
+ 普通插件命令使用 `pi.command`,目标插件只需已在 Pi 中注册命令,不需要实现本文的协议。`pi.message` 和 `pi.command` 由 onward 内置的 Pi 适配模块注册,无需额外安装;这两个名称属于 onward 的动作命名空间,并非 Pi 官方 API。本文用于独立桥接扩展或插件主动提供结构化能力。
4
4
 
5
5
  ## 发现与加载
6
6
 
@@ -54,7 +54,7 @@ export default function (pi: ExtensionAPI) {
54
54
  | `failures` | 本次恢复过程中的连续失败次数 |
55
55
  | `minFailures` | 所选阶段的连续失败次数下限,包含当前失败 |
56
56
  | `failure` | 只读失败快照:kind、text、provider、model |
57
- | `taskPrompt` | 可选的任务提示词文本快照;用于 `{taskPrompt}`,自动续跑不覆盖来源 |
57
+ | `taskPrompt` | 可选的已接收任务文本快照;用于 `{taskPrompt}`,自动消息保留来源,重载后按会话记录重建 |
58
58
  | `chain` | 只读恢复链:id、handoffs、maxHandoffs |
59
59
  | `signal` | 合并取消及动作执行时限的信号 |
60
60
 
@@ -92,6 +92,6 @@ pi.events.emit("onward:resume-recovery", {
92
92
  });
93
93
  ```
94
94
 
95
- onward 在工厂初始化时已监听此事件,支持在它自己的 session_start 之前或之后收到。错误的会话 ID 不生效。人工新任务或正常模型进展结束恢复链;自动注入的消息保留当前链。
95
+ onward 在工厂初始化时已监听此事件,支持在它自己的 session_start 之前或之后收到。错误的会话 ID 不生效。已接收的人工新任务或正常模型进展结束恢复链;自动注入的消息保留当前链。
96
96
 
97
97
  通用 slash 命令没有上述约定,也没有业务结果回执,因此不能推断恢复链已传递。跨会话或跨进程的防循环由目标扩展负责。独立桥接扩展也不能通过包装命令声称获得了命令没有公开的确认、取消或去重能力。
package/example.json CHANGED
@@ -20,7 +20,7 @@
20
20
  "failure": "\\b(401|429|500|502|503|504|529)\\b|connection|network|fetch failed|timed? ?out|overloaded"
21
21
  },
22
22
  "stages": [
23
- { "minFailures": 1, "delay": "3s..15s", "action": { "use": "onward.resend" } },
23
+ { "minFailures": 1, "delay": "3s..15s", "action": { "use": "pi.message", "with": { "prompt": "{taskPrompt}" } } },
24
24
  { "minFailures": 4, "action": { "use": "onward.stop", "with": { "reason": "连续失败 4 次,请检查服务或配置恢复插件动作" } } }
25
25
  ]
26
26
  },
@@ -28,7 +28,7 @@
28
28
  "name": "empty",
29
29
  "when": { "failure": "^$" },
30
30
  "stages": [
31
- { "minFailures": 1, "delay": "3s", "action": { "use": "onward.message", "with": { "prompt": "请继续执行任务:\n{taskPrompt}" } } },
31
+ { "minFailures": 1, "delay": "3s", "action": { "use": "pi.message", "with": { "prompt": "请继续执行任务:\n{taskPrompt}" } } },
32
32
  { "minFailures": 3, "action": { "use": "onward.stop" } }
33
33
  ]
34
34
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cobia/pi-onward",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "pi 出错或空回复时,按阶段策略恢复并调用扩展命令或具名动作",
5
5
  "keywords": [
6
6
  "pi",
@@ -1,60 +1,12 @@
1
1
  /** Built-ins implement exactly the same contract as external actions. */
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { piActions } from "./pi.ts";
3
4
  import type { ActionDefinition } from "./protocol.ts";
4
5
 
5
- export const CUSTOM_TYPE = "pi-onward";
6
6
  const modes = ["tui", "rpc", "json", "print"] as const;
7
- const empty = { type: "object", properties: {}, additionalProperties: false };
8
7
  export function builtinActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserMessage">): ActionDefinition[] {
9
8
  return [
10
- {
11
- name: "onward.resend",
12
- description: "从模型上下文省略失败回复,重发请求",
13
- phase: "boundary",
14
- modes,
15
- parameters: empty,
16
- execute(_params, context) {
17
- return {
18
- kind: "continue",
19
- entries: [{ type: "context_edit", targetId: context.targetId, replacement: null }],
20
- };
21
- },
22
- },
23
- {
24
- name: "onward.message",
25
- description: "发送一条消息续跑",
26
- phase: "boundary",
27
- modes,
28
- parameters: {
29
- type: "object",
30
- properties: { prompt: { type: "string", pattern: "\\S", maxLength: 4000, default: "继续" } },
31
- additionalProperties: false,
32
- },
33
- execute(params, context) {
34
- const prompt = String(params.prompt ?? "继续");
35
- if (prompt.includes("{taskPrompt}") && !context.taskPrompt?.trim())
36
- return { kind: "failed", message: "No task prompt is available to expand {taskPrompt}" };
37
- const vars: Record<string, string> = {
38
- failures: String(context.failures),
39
- rule: context.rule,
40
- error: context.failure.text || "空回复",
41
- taskPrompt: context.taskPrompt ?? "",
42
- };
43
- const content = prompt.replace(/\{(failures|rule|error|taskPrompt)\}/g, (_, key: string) => vars[key]!);
44
- return {
45
- kind: "continue",
46
- entries: [
47
- {
48
- type: "custom_message",
49
- customType: CUSTOM_TYPE,
50
- content,
51
- display: true,
52
- details: { rule: context.rule, failures: context.failures, invocationId: context.invocationId },
53
- },
54
- ],
55
- };
56
- },
57
- },
9
+ ...piActions(pi),
58
10
  {
59
11
  name: "onward.stop",
60
12
  description: "停止本次自动恢复",
@@ -69,30 +21,5 @@ export function builtinActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserM
69
21
  return { kind: "stopped", message: String(params.reason ?? "规则要求停止,请处理失败原因后再发消息") };
70
22
  },
71
23
  },
72
- {
73
- name: "onward.command",
74
- description: "分派已加载的扩展命令;业务结果未知",
75
- phase: "settled",
76
- modes,
77
- parameters: {
78
- type: "object",
79
- required: ["name"],
80
- additionalProperties: false,
81
- properties: { name: { type: "string", pattern: "^[^/\\s]+$" }, args: { type: "string" } },
82
- },
83
- execute(params, context) {
84
- if (context.signal.aborted) return { kind: "cancelled", message: "命令分派已取消" };
85
- const name = String(params.name);
86
- if (name === "onward" || name.startsWith("onward:"))
87
- return { kind: "failed", message: "Cannot automatically invoke onward's own control commands" };
88
- if (!pi.getCommands().some((command) => command.source === "extension" && command.name === name))
89
- return {
90
- kind: "failed",
91
- message: `Extension command /${name} is not loaded; no text was sent to the model`,
92
- };
93
- pi.sendUserMessage(`/${name}${params.args ? ` ${params.args}` : ""}`, { expandPromptTemplates: true });
94
- return { kind: "dispatched", message: `已分派 /${name};完成情况由目标插件报告` };
95
- },
96
- },
97
24
  ];
98
25
  }
@@ -0,0 +1,70 @@
1
+ /** Pi message and command adapters, registered through the same interface as external actions. */
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import type { ActionDefinition } from "./protocol.ts";
4
+
5
+ export const CUSTOM_TYPE = "pi-onward";
6
+ const modes = ["tui", "rpc", "json", "print"] as const;
7
+ export function piActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserMessage">): ActionDefinition[] {
8
+ return [
9
+ {
10
+ name: "pi.message",
11
+ description: "发送一条消息续跑",
12
+ phase: "boundary",
13
+ modes,
14
+ parameters: {
15
+ type: "object",
16
+ properties: { prompt: { type: "string", pattern: "\\S", maxLength: 4000, default: "继续" } },
17
+ additionalProperties: false,
18
+ },
19
+ execute(params, context) {
20
+ const prompt = String(params.prompt ?? "继续");
21
+ if (prompt.includes("{taskPrompt}") && !context.taskPrompt?.trim())
22
+ return { kind: "failed", message: "No task prompt is available to expand {taskPrompt}" };
23
+ const vars: Record<string, string> = {
24
+ failures: String(context.failures),
25
+ rule: context.rule,
26
+ error: context.failure.text || "空回复",
27
+ taskPrompt: context.taskPrompt ?? "",
28
+ };
29
+ const content = prompt.replace(/\{(failures|rule|error|taskPrompt)\}/g, (_, key: string) => vars[key]!);
30
+ return {
31
+ kind: "continue",
32
+ entries: [
33
+ {
34
+ type: "custom_message",
35
+ customType: CUSTOM_TYPE,
36
+ content,
37
+ display: true,
38
+ details: { rule: context.rule, failures: context.failures, invocationId: context.invocationId },
39
+ },
40
+ ],
41
+ };
42
+ },
43
+ },
44
+ {
45
+ name: "pi.command",
46
+ description: "分派已加载的扩展命令;业务结果未知",
47
+ phase: "settled",
48
+ modes,
49
+ parameters: {
50
+ type: "object",
51
+ required: ["name"],
52
+ additionalProperties: false,
53
+ properties: { name: { type: "string", pattern: "^[^/\\s]+$" }, args: { type: "string" } },
54
+ },
55
+ execute(params, context) {
56
+ if (context.signal.aborted) return { kind: "cancelled", message: "命令分派已取消" };
57
+ const name = String(params.name);
58
+ if (name === "onward" || name.startsWith("onward:"))
59
+ return { kind: "failed", message: "Cannot automatically invoke onward's own control commands" };
60
+ if (!pi.getCommands().some((command) => command.source === "extension" && command.name === name))
61
+ return {
62
+ kind: "failed",
63
+ message: `Extension command /${name} is not loaded; no text was sent to the model`,
64
+ };
65
+ pi.sendUserMessage(`/${name}${params.args ? ` ${params.args}` : ""}`, { expandPromptTemplates: true });
66
+ return { kind: "dispatched", message: `已分派 /${name};完成情况由目标插件报告` };
67
+ },
68
+ },
69
+ ];
70
+ }
@@ -40,7 +40,7 @@ interface Execution {
40
40
  failures: number;
41
41
  minFailures: number;
42
42
  failure: Readonly<FailureSnapshot>;
43
- /** Task input text, kept stable across automatically generated continuation messages. */
43
+ /** Accepted task text, rebuilt from persisted input origins and stable across automatic continuations. */
44
44
  taskPrompt?: string;
45
45
  chain: Readonly<RecoveryChain>;
46
46
  signal: AbortSignal;
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { CUSTOM_TYPE } from "../actions/builtins.ts";
2
+ import { CUSTOM_TYPE } from "../actions/pi.ts";
3
3
  import { Recovery } from "../runtime/recovery.ts";
4
4
  import { argumentTabCompletion } from "./autocomplete.ts";
5
5
  import { registerCommand } from "./command.ts";
@@ -21,6 +21,7 @@ export function install(pi: ExtensionAPI, paths: ConfigPaths): void {
21
21
  if (notice) say(ctx, notice);
22
22
  });
23
23
  pi.on("input", (event, ctx) => onward.input(event, ctx));
24
+ pi.on("before_agent_start", (event, ctx) => onward.beforeAgentStart(event, ctx));
24
25
  pi.on("session_tree", (_event, ctx) => onward.branch(ctx));
25
26
  pi.on("agent_start", (_event, ctx) => onward.agentStart(ctx));
26
27
  pi.on("message_end", (event, ctx) => onward.messageEnd(event, ctx));
@@ -120,7 +120,7 @@ function parseStages(raw: unknown, label: string, problems: string[]): Stage[] {
120
120
  }
121
121
  unknownKeys(action, new Set(["use", "with"]), `${at}.action`, problems);
122
122
  if (typeof action.use !== "string" || !new RegExp(ACTION_NAME_PATTERN).test(action.use))
123
- problems.push(`${at}.action.use must be a qualified action name such as onward.resend`);
123
+ problems.push(`${at}.action.use must be a qualified action name such as pi.message`);
124
124
  if (action.with !== undefined && !isRecord(action.with)) problems.push(`${at}.action.with must be an object`);
125
125
  if (problems.length === before && typeof delay !== "string")
126
126
  stages.push({
@@ -5,6 +5,7 @@ import type {
5
5
  AgentBeforeSettleEvent,
6
6
  AgentBeforeSettleEventResult,
7
7
  AgentSettledEvent,
8
+ BeforeAgentStartEvent,
8
9
  ExtensionAPI,
9
10
  ExtensionCommandContext,
10
11
  ExtensionContext,
@@ -28,6 +29,7 @@ import { failureText, isFailure, isSuccess } from "../policy/failure.ts";
28
29
  import { resolveLimits } from "../policy/policy.ts";
29
30
  import { errorText, isRecord } from "../util.ts";
30
31
  import { Episode } from "./episode.ts";
32
+ import { INPUT_RECORD, TaskPrompt } from "./task-prompt.ts";
31
33
 
32
34
  export interface RunState {
33
35
  phase: "idle" | "waiting" | "submitted" | "retrying" | "queued" | "executing" | "stopped";
@@ -64,7 +66,7 @@ export class Recovery {
64
66
  private pending: Invocation | undefined;
65
67
  private disposed = false;
66
68
  private sessionId: string | undefined;
67
- private taskPrompt: string | undefined;
69
+ private readonly taskPrompt = new TaskPrompt();
68
70
  private statusText: string | undefined;
69
71
  private restored: { sessionId: string; chain: RecoveryChain } | undefined;
70
72
  constructor(
@@ -92,17 +94,10 @@ export class Recovery {
92
94
  this.restored = undefined;
93
95
  }
94
96
  input(event: InputEvent, ctx: ExtensionContext): void {
95
- if (!this.owns(ctx) || this.disposed) return;
96
- if (event.source !== "extension") {
97
- this.taskPrompt = event.text;
98
- this.reset(ctx);
99
- } else {
100
- this.taskPrompt ??= event.text;
101
- // Automatic prompts continue the same budget; only a real user task starts a fresh episode.
102
- this.pending?.controller.abort();
103
- this.pending = undefined;
104
- this.setState(ctx, { phase: "idle" });
105
- }
97
+ if (this.owns(ctx)) this.taskPrompt.observe(event);
98
+ }
99
+ beforeAgentStart(event: BeforeAgentStartEvent, ctx: ExtensionContext): void {
100
+ if (this.owns(ctx)) this.taskPrompt.begin(event);
106
101
  }
107
102
  agentStart(ctx: ExtensionContext): void {
108
103
  if (!this.owns(ctx)) return;
@@ -123,7 +118,20 @@ export class Recovery {
123
118
  }
124
119
  }
125
120
  messageEnd(event: MessageEndEvent, ctx: ExtensionContext): void {
126
- if (this.owns(ctx) && isSuccess(event.message)) this.reset(ctx);
121
+ if (!this.owns(ctx)) return;
122
+ if (event.message.role === "user") {
123
+ const source = this.taskPrompt.consume();
124
+ // Pi persists the user message after message_end handlers. This metadata follows the same branch,
125
+ // contains no duplicate prompt text and never enters model context.
126
+ this.pi.appendEntry(INPUT_RECORD, { timestamp: event.message.timestamp, source: source ?? "unknown" });
127
+ if (source === "user") this.reset(ctx);
128
+ else {
129
+ // A consumed automatic message cancels stale work but preserves the recovery budget.
130
+ this.pending?.controller.abort();
131
+ this.pending = undefined;
132
+ this.setState(ctx, { phase: "idle" });
133
+ }
134
+ } else if (isSuccess(event.message)) this.reset(ctx);
127
135
  }
128
136
  async beforeSettle(
129
137
  event: AgentBeforeSettleEvent,
@@ -166,6 +174,7 @@ export class Recovery {
166
174
  this.finish(ctx, { kind: "stopped", message: `达到跨会话接管上限 ${chain.maxHandoffs} 次` }, hit);
167
175
  return;
168
176
  }
177
+ this.taskPrompt.refresh(ctx.sessionManager.getBranch());
169
178
  const invocation: Invocation = {
170
179
  id: randomUUID(),
171
180
  hit,
@@ -174,7 +183,7 @@ export class Recovery {
174
183
  controller: new AbortController(),
175
184
  config: this.settings.config,
176
185
  sessionId: ctx.sessionManager.getSessionId(),
177
- taskPrompt: this.taskPrompt,
186
+ taskPrompt: this.taskPrompt.value,
178
187
  };
179
188
  this.pending = invocation;
180
189
  const signal = ctx.signal
@@ -212,6 +221,7 @@ export class Recovery {
212
221
  }
213
222
  settled(event: AgentSettledEvent, ctx: ExtensionContext): void {
214
223
  if (!this.owns(ctx)) return;
224
+ if (!ctx.hasPendingMessages()) this.taskPrompt.clearPending();
215
225
  if (event.aborted) {
216
226
  if (this.pending) this.cancel(ctx, "用户取消了恢复");
217
227
  return;
@@ -277,27 +287,14 @@ export class Recovery {
277
287
  }
278
288
  branch(ctx: ExtensionContext): void {
279
289
  if (!this.owns(ctx)) return;
280
- this.taskPrompt = undefined;
281
- const entries = ctx.sessionManager.getBranch();
282
- for (let index = entries.length - 1; index >= 0; index--) {
283
- const entry = entries[index]!;
284
- if (entry.type !== "message" || entry.message.role !== "user") continue;
285
- const content = entry.message.content;
286
- this.taskPrompt =
287
- typeof content === "string"
288
- ? content
289
- : content
290
- .filter((part) => part.type === "text")
291
- .map((part) => part.text)
292
- .join("\n");
293
- break;
294
- }
290
+ this.taskPrompt.restore(ctx.sessionManager.getBranch());
295
291
  this.reset(ctx);
296
292
  }
297
293
  stop(ctx: ExtensionContext): void {
298
294
  if (this.owns(ctx)) this.reset(ctx);
299
295
  }
300
296
  shutdown(ctx: ExtensionContext): void {
297
+ this.taskPrompt.clearPending();
301
298
  this.pending?.controller.abort();
302
299
  this.pending = undefined;
303
300
  this.disposed = true;
@@ -0,0 +1,82 @@
1
+ /** Resolve consumed input origins and rebuild task text from records on the current branch. */
2
+ import type { BeforeAgentStartEvent, InputEvent, MessageEndEvent, SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import { isRecord } from "../util.ts";
4
+
5
+ export const INPUT_RECORD = "onward.input";
6
+ type InputOrigin = "user" | "extension";
7
+ type UserMessage = Extract<MessageEndEvent["message"], { role: "user" }>;
8
+
9
+ export class TaskPrompt {
10
+ value: string | undefined;
11
+ private nextRun: InputOrigin[] = [];
12
+ private starting: { source: InputOrigin | undefined } | undefined;
13
+ private queued: InputOrigin[] = [];
14
+
15
+ observe(event: InputEvent): void {
16
+ // Later input handlers may transform or handle it. Observation alone never changes a task.
17
+ const candidates = event.streamingBehavior === undefined ? this.nextRun : this.queued;
18
+ candidates.push(event.source === "extension" ? "extension" : "user");
19
+ }
20
+ begin(event: BeforeAgentStartEvent): void {
21
+ if (event.messageType !== "user") return;
22
+ this.starting = { source: commonOrigin(this.nextRun) };
23
+ this.nextRun = [];
24
+ }
25
+ consume(): InputOrigin | undefined {
26
+ if (this.starting) {
27
+ const { source } = this.starting;
28
+ this.starting = undefined;
29
+ return source;
30
+ }
31
+ const source = commonOrigin(this.queued);
32
+ if (source !== undefined) this.queued.shift();
33
+ return source;
34
+ }
35
+ clearPending(): void {
36
+ this.nextRun = [];
37
+ this.starting = undefined;
38
+ this.queued = [];
39
+ }
40
+ restore(branch: readonly SessionEntry[]): void {
41
+ this.clearPending();
42
+ this.refresh(branch);
43
+ }
44
+ refresh(branch: readonly SessionEntry[]): void {
45
+ this.value = undefined;
46
+ let hasUser = false;
47
+ let record: { timestamp: number; source: InputOrigin | undefined } | undefined;
48
+ for (const entry of branch) {
49
+ if (entry.type === "custom" && entry.customType === INPUT_RECORD) {
50
+ const data = entry.data;
51
+ record =
52
+ isRecord(data) && typeof data.timestamp === "number"
53
+ ? { timestamp: data.timestamp, source: inputOrigin(data.source) }
54
+ : undefined;
55
+ } else if (entry.type === "message" && entry.message.role === "user") {
56
+ // message_end appends the record just before Pi persists its user message. A branch cut
57
+ // before that message must not adopt the dangling record as its task.
58
+ const source = record && record.timestamp === entry.message.timestamp ? record.source : undefined;
59
+ if (source === undefined) this.value = undefined;
60
+ else if (source === "user" || !hasUser) this.value = userText(entry.message);
61
+ hasUser = true;
62
+ record = undefined;
63
+ }
64
+ }
65
+ }
66
+ }
67
+ function inputOrigin(value: unknown): InputOrigin | undefined {
68
+ return value === "user" || value === "extension" ? value : undefined;
69
+ }
70
+ function commonOrigin(candidates: readonly InputOrigin[]): InputOrigin | undefined {
71
+ // Pi does not expose an accepted-input ID or a source on user messages. Text equality cannot
72
+ // prove origin after transforms/handled inputs. Mixed origins stay unknown until settlement.
73
+ return candidates.every((source) => source === candidates[0]) ? candidates[0] : undefined;
74
+ }
75
+ function userText(message: UserMessage): string {
76
+ return typeof message.content === "string"
77
+ ? message.content
78
+ : message.content
79
+ .filter((part) => part.type === "text")
80
+ .map((part) => part.text)
81
+ .join("\n");
82
+ }