@criogaid/pi-hashline-edit 0.14.0 → 0.15.0
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 +4 -4
- package/README.zh-CN.md +4 -4
- package/package.json +1 -1
- package/src/pi/AGENTS.md +6 -6
- package/src/pi/action-fusion.ts +39 -76
- package/src/pi/argument-validation.ts +30 -16
- package/src/pi/fusion-arguments.ts +214 -0
- package/src/pi/fusion-card.ts +4 -8
- package/src/pi/mutation-result.ts +14 -16
- package/src/pi/mutation-runner.ts +22 -20
- package/src/pi/native-bash.ts +41 -0
- package/src/pi/report-schema.ts +23 -11
- package/src/pi/report.ts +3 -4
package/README.md
CHANGED
|
@@ -79,7 +79,7 @@ The extension replaces Pi's `read`, `grep`, `edit`, and `write`, and adds `repla
|
|
|
79
79
|
| `replace` | Applies literal or regex substitutions across one file. Every rule must match, and overlapping matches reject the batch. |
|
|
80
80
|
| `write` | Creates a file (`mode: "create"`) or overwrites one (`mode: "overwrite"`), using the content exactly as given. Missing parent directories are created. |
|
|
81
81
|
|
|
82
|
-
Scripts that call these tools, such as Pi's codemode, receive each successful result as one object in place of the result text: the fields its report states, preceded for `read` and `grep` by the payload as `text`. The object also has the facts the report leaves out because the payload or the call already shows them: every `grep` result has `matches` and `files`; a `read` that returns at least one line has `nextOffset` whenever lines remain after it, including when the caller's `limit` ends the window (a first line too long to fit returns no line, so the result has `lineTooLong` and no `nextOffset`); and a change
|
|
82
|
+
Scripts that call these tools, such as Pi's codemode, receive each successful result as one object in place of the result text: the fields its report states, preceded for `read` and `grep` by the payload as `text`. The object also has the facts the report leaves out because the payload or the call already shows them: every `grep` result has `matches` and `files`; a `read` that returns at least one line has `nextOffset` whenever lines remain after it, including when the caller's `limit` ends the window (a first line too long to fit returns no line, so the result has `lineTooLong` and no `nextOffset`); and a change with `then_run` includes its status and any native Bash structured fields. For example, a read cut by its default line limit is `{ text, nextOffset, next }` and a created file is `{ publication }`; reading an image gives Pi's image block, and a file containing NUL bytes gives `{ text }` with Pi's own read output, whose continuation notice is part of that text. A `write`, `edit`, or `replace` whose result equals the file's current content is not a failure: the call resolves with `publication: "NOT_PUBLISHED"`, and nothing is written. A failed call rejects with its report text.
|
|
83
83
|
|
|
84
84
|
### Paths
|
|
85
85
|
|
|
@@ -131,7 +131,7 @@ Argument and anchor validation failures leave the file untouched. The report nam
|
|
|
131
131
|
|
|
132
132
|
A failure during or after publication states `NOT_PUBLISHED`, `PUBLISHED`, or `UNKNOWN`. Follow the report's `next` before retrying: an error after publication can leave the requested change on disk.
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
Errors in the file operation's arguments, including a reversed range, are reported per field before file access, with the field's meaning and how to fix it. A regex syntax error in `grep` or `replace` keeps V8's diagnostic and adds a `fix`: use `literal: true` for exact text, or correct the intended regex. The tool never switches modes automatically.
|
|
135
135
|
|
|
136
136
|
## Action Fusion
|
|
137
137
|
|
|
@@ -145,7 +145,7 @@ Argument mistakes, including a reversed range, are reported per field, with what
|
|
|
145
145
|
}
|
|
146
146
|
```
|
|
147
147
|
|
|
148
|
-
The command runs through the session's own Bash tool, so approvals, overrides, and hooks still apply. Fusion checks that the change succeeded and the file is still as written before handing the command to the session. It checks the file again after the command settles; an outside writer can still change it while approval is pending or while the command runs. A failing command never rolls back the file. The
|
|
148
|
+
The command runs through the session's own Bash tool, so approvals, overrides, and hooks still apply. Fusion checks that the change succeeded and the file is still as written before handing the command to the session. It checks the file again after the command settles; an outside writer can still change it while approval is pending or while the command runs. Invalid `then_run` arguments still let a valid file operation complete. The result states the actual `publication`, reports `then_run.status` as `failed`, and shows the argument diagnostic. Bash is not started. To retry, correct the arguments and call `bash` directly. A failing command never rolls back the file. The model receives the final session Bash text and image content blocks in order, with native formatting, limits and truncation, followed by a separate change report whose `then_run` states the command's status. Hashline does not apply its field budget to these blocks. Scripts receive `then_run.status` and, when supplied by Bash, `output` (raw stdout/stderr, possibly empty), `truncated`, optional `full_output_path`, `exit_code`, and `wall_time_seconds`. A permission block, timeout, skipped command, or override without a native structured result can provide status alone; diagnostics appear in content. A Bash override that calls a mutation tool for a target already in the Fusion queue receives an error rather than waiting on that queue. The TUI shows the change and the command as separate cards, with a countdown from the effective Bash timeout once Bash reports execution progress.
|
|
149
149
|
|
|
150
150
|
Cancelling a mutation while it waits in the Fusion queue stops that call before it writes. The earlier mutation and command keep their place in the queue.
|
|
151
151
|
|
|
@@ -187,7 +187,7 @@ The Pi workspace (the SDK session's `cwd` when embedded) is the base for both `.
|
|
|
187
187
|
|
|
188
188
|
The selected model's declared context capacity sets the output budgets; remaining context is never used. A known capacity counts as one byte per context token, up to 4 MiB. Anchored read rows receive a quarter of it and grep payloads an eighth (each at least 512 bytes); a 384,000-token model gets 93.8 KiB per read and 46.9 KiB per grep. Diagnostic blocks receive a quarter of the capacity (at least 512 bytes), and free-text fields a quarter of the block budget (at least 128 bytes). Grep previews keep one UTF-16 code unit per 100 bytes of grep payload and at least 500. A file's first row is narrowed further when it would not otherwise fit the payload after the file's header, and `linePreviewLimit` states the narrowest preview shown. The definitions and fallback values live in [`budgets.ts`](src/pi/budgets.ts).
|
|
189
189
|
|
|
190
|
-
Argument rejections fit their diagnostic block as serialized JSON. In edit failures, the failure list and the candidate neighborhoods each fit a block in compact JSON, with whole entries or rows omitted and counted; so do replace's list of unmatched rules and the list of missing paths.
|
|
190
|
+
Argument rejections fit their diagnostic block as serialized JSON. In edit failures, the failure list and the candidate neighborhoods each fit a block in compact JSON, with whole entries or rows omitted and counted; so do replace's list of unmatched rules and the list of missing paths.
|
|
191
191
|
|
|
192
192
|
When model capacity is unknown or invalid, the defaults are 64 KiB for read rows, 50 KiB for grep payloads, 16 KiB per diagnostic block, 4 KiB per free-text field, and 500 UTF-16 code units per grep preview. An explicit `read.maxKiB` overrides only the read cap. Each execution keeps the budget snapshot it started with.
|
|
193
193
|
|
package/README.zh-CN.md
CHANGED
|
@@ -79,7 +79,7 @@ greet.ts · 3 lines
|
|
|
79
79
|
| `replace` | 在单个文件内批量执行字面或正则替换。每条规则都必须有匹配,匹配区域重叠时整批拒绝。 |
|
|
80
80
|
| `write` | 新建文件(`mode: "create"`)或覆盖文件(`mode: "overwrite"`),内容原样写入,缺失的父目录会一并创建。 |
|
|
81
81
|
|
|
82
|
-
调用这些工具的脚本(例如 Pi 的 codemode)拿到的每个成功结果是一个对象,而不是结果文本:对象里是报告的各个字段,`read` 和 `grep` 另把正文放在 `text` 里。报告因为正文或调用本身已经体现而省略的事实,对象里也有:`grep` 的结果始终带 `matches` 和 `files`;`read` 至少返回一行且其后还有行时始终带 `nextOffset`,包括窗口由调用方的 `limit` 截止的情况(首行过长放不下时不返回任何行,结果带 `lineTooLong`,不带 `nextOffset`);带 `then_run`
|
|
82
|
+
调用这些工具的脚本(例如 Pi 的 codemode)拿到的每个成功结果是一个对象,而不是结果文本:对象里是报告的各个字段,`read` 和 `grep` 另把正文放在 `text` 里。报告因为正文或调用本身已经体现而省略的事实,对象里也有:`grep` 的结果始终带 `matches` 和 `files`;`read` 至少返回一行且其后还有行时始终带 `nextOffset`,包括窗口由调用方的 `limit` 截止的情况(首行过长放不下时不返回任何行,结果带 `lineTooLong`,不带 `nextOffset`);带 `then_run` 的修改包含命令状态和 Bash 提供的原生结构化字段。例如,被默认行数截断的读取是 `{ text, nextOffset, next }`,新建文件是 `{ publication }`;读图片时拿到 Pi 的图片块;读含 NUL 字节的文件时拿到 `{ text }`,内容是 Pi 原版 read 的输出,续读提示写在这段文本里。`write`、`edit`、`replace` 的结果和文件现有内容相同时不算失败:调用正常返回,`publication` 是 `NOT_PUBLISHED`,没有写入任何内容。调用失败时脚本收到异常,内容是报告文本。
|
|
83
83
|
|
|
84
84
|
### 路径
|
|
85
85
|
|
|
@@ -131,7 +131,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
131
131
|
|
|
132
132
|
发布期间或发布后的失败会明确标记 `NOT_PUBLISHED`、`PUBLISHED` 或 `UNKNOWN`。重试前应遵循报告的 `next`:发布后的错误可能意味着所需修改已经写入磁盘。
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
文件操作本身的参数有误(包括范围写反)时,工具在访问文件前逐项报告字段的含义和修正方法。`grep` 或 `replace` 的正则语法错误保留 V8 原始诊断,并附带 `fix`:原样匹配文本时用 `literal: true`,确实需要正则时修正表达式。工具不会自动切换模式。
|
|
135
135
|
|
|
136
136
|
## Action Fusion
|
|
137
137
|
|
|
@@ -145,7 +145,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
145
145
|
}
|
|
146
146
|
```
|
|
147
147
|
|
|
148
|
-
命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。Fusion
|
|
148
|
+
命令通过会话自己的 Bash 工具执行,审批、覆盖和钩子照常生效。Fusion 把命令交给会话前,会确认修改成功且文件仍是刚写入的内容;命令结束后会再次检查。其他写入者仍可能在等待审批或命令执行时改动文件。`then_run` 参数有误时,有效的文件操作仍会完成。结果里的 `publication` 表示文件的实际发布状态,`then_run.status` 为 `failed`,并附有具体的参数诊断。Bash 不会启动。要重试命令,修正参数后单独调用 `bash` 即可。命令失败不会回滚文件。模型按顺序收到会话 Bash 最终结果的文本和图片内容块,保留原生格式、限制和截断,后面是独立的修改报告,其中 `then_run` 写明命令状态。Hashline 不对这些内容块应用字段预算。脚本收到 `then_run.status`,以及 Bash 提供的原生结构化字段:`output`(原始标准输出和标准错误,可以为空)、`truncated`、可选的 `full_output_path`、`exit_code` 和 `wall_time_seconds`。审批拦截、超时、跳过命令或未提供原生结构化结果的覆盖可以只有状态;诊断信息显示在内容中。如果自定义 Bash 调用修改类工具,而目标已在 Fusion 队列中,这次修改会直接报错,不会等待队列。TUI 把修改和命令分成两张卡片显示,Bash 发出第一条执行进度后,命令卡片按实际生效的超时值倒计时。
|
|
149
149
|
|
|
150
150
|
修改调用在 Fusion 队列中等待时可以取消,取消后不会写入文件。前面的修改和命令仍占有队列。
|
|
151
151
|
|
|
@@ -187,7 +187,7 @@ grep 卡片原样显示返回的文件路径和计数行。只有 `content` 模
|
|
|
187
187
|
|
|
188
188
|
输出预算根据所选模型声明的上下文容量计算,不使用剩余上下文。容量已知时按每上下文 token 一字节计,最高 4 MiB。带锚点的 read 行获得其四分之一,grep 载荷获得八分之一,各至少 512 字节;384,000 token 的模型每次 read 为 93.8 KiB,每次 grep 为 46.9 KiB。诊断块获得容量的四分之一,至少 512 字节;自由文本字段获得诊断块预算的四分之一,至少 128 字节。Grep 预览按每 100 字节 grep 载荷保留一个 UTF-16 单元,至少 500 个。文件的第一行若放在文件标题之后会超出载荷,就进一步缩窄到放得下为止,`linePreviewLimit` 报告所显示预览中最窄的宽度。定义和回退值位于 [`budgets.ts`](src/pi/budgets.ts)。
|
|
189
189
|
|
|
190
|
-
参数拒绝报告序列化为 JSON 后不超过诊断块预算。编辑失败时,失败条目列表和候选锚点的上下文各按紧凑 JSON 计入一个诊断块,只省略完整条目或整行,并给出省略数量;replace
|
|
190
|
+
参数拒绝报告序列化为 JSON 后不超过诊断块预算。编辑失败时,失败条目列表和候选锚点的上下文各按紧凑 JSON 计入一个诊断块,只省略完整条目或整行,并给出省略数量;replace 未匹配的规则列表和缺失路径列表同样如此。
|
|
191
191
|
|
|
192
192
|
模型容量未知或非法时,默认上限为 read 行 64 KiB、grep 载荷 50 KiB、每个诊断块 16 KiB、每个自由文本字段 4 KiB、每条 grep 预览 500 个 UTF-16 单元。显式设置 `read.maxKiB` 只覆盖 read 上限。每次执行使用开始时取得的预算快照。
|
|
193
193
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@criogaid/pi-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Hash-anchored file editing for Pi: line edits cite anchors that are checked against the current file before any write.",
|
|
6
6
|
"homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
|
package/src/pi/AGENTS.md
CHANGED
|
@@ -8,21 +8,21 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
|
|
|
8
8
|
|
|
9
9
|
## Argument funnel
|
|
10
10
|
|
|
11
|
-
- Call order: a tool's `prepareArguments
|
|
11
|
+
- Call order: a tool's `prepareArguments`, then Pi's schema validation and mutable `tool_call` hooks, then an owned snapshot at `execute`. The tool checks that snapshot against the same schema and semantic rules without coercing hook edits. Caller arguments are never rewritten. File-dependent checks stay in execution.
|
|
12
12
|
- Tool files define TypeBox schemas, and each mutation tool's description names its alternative (edit ↔ replace ↔ write). A tool supplies only the semantic checks its schema cannot express or name precisely: edit's per-action fields and ranges, text that cannot be written as UTF-8, and regex compilation through `checkRegexArguments` in `argument-validation.ts`, which reports flags V8 rejects and compiles regex-mode patterns under the flags each tool uses. Shared integer rules live in `schema.ts`.
|
|
13
13
|
- Every tool declares `STRICT_SAMPLING` from `schema.ts` (mutation tools through `mutationToolBase`) and keeps its parameters convertible by Pi's strict converter: no object or array unions, so grep's multi-valued fields are arrays only and each edit item is one flat object whose `EDIT_OPS` table, not the schema, fixes the fields per action.
|
|
14
14
|
- Some providers emit keys in declaration order and others alphabetically, so the `edit` and `replace` keys are declared in alphabetical order (`path`, `steps`, `then_run`; `action`, `anchor`, `end`, `lines`; `path`, `replacements`, `then_run`): both orders stream the file and each operation's action and range before the payload.
|
|
15
|
-
- `argument-validation.ts` owns
|
|
15
|
+
- `argument-validation.ts` owns the shared preparation and final-snapshot checks, issue collection, bounded diagnostic output, and the Pi schema validation adapter. `fusion-arguments.ts` applies this boundary separately to the file operation and its optional `then_run`. It coerces one copy with Pi's schema engine, formats, and unresolved-reference policy. The schema check, semantic checks, and failure diagnostics use that copy. Tools report semantic field issues through the callback without throwing during collection. The boundary parses each local path spelling, reporting Node's reason for an invalid file URL. Execution receives the original spelling and the absolute path resolved against the tool's cwd. The edit check parses anchors during semantic validation and builds core steps only for the accepted execution snapshot. The boundary checks array shape on structured-clone snapshots of the arguments (enumerable own string-keyed properties of ordinary objects and arrays) before preparation coercion and before post-hook semantic checks. Arrays in either snapshot must have no holes or named properties. Both checks follow the item schema for a singleton at its original path, where Pi wraps it; the schema check still rejects a singleton a hook leaves at an array field. Execution uses the checked post-hook snapshot. Preparation hands Pi the same raw snapshot for coercion and validation. Pi's coercion is copy-on-write. Do not reimplement coercion or optional-null rules.
|
|
16
16
|
- `argument-diagnostics.ts` owns failure-only schema projection and structured aggregation. Top-level tool fields have independent schemas; failure diagnosis derives field schemas with TypeBox and keeps Pi's coercion and per-field error limits. Derive choices and the explanations of missing, undeclared, pattern-mismatched, and out-of-choice fields from the declared schema: when a schema reason does not say how to correct the value, the `fix` of a missing field, a pattern mismatch, or a value outside the field's choices is the field's description (each choice's value and description), and an undeclared field's `fix` lists its object's accepted fields. A declared field is applicable even when absent, so a tool check may require it. An issue on a whole object leaves its fields' diagnostics in place. Suppress only inapplicable or already explained issues, and retain independent fields with bounded native diagnostics.
|
|
17
17
|
- `argument-error.ts` owns the JSON argument-error envelope and its byte budget: retain exact field paths, omit whole issues with explicit counts, and never truncate serialized JSON or repeat the call's arguments. Preparation failures use the same envelope.
|
|
18
18
|
|
|
19
19
|
## Mutations
|
|
20
20
|
|
|
21
|
-
- `mutation-runner.ts` owns what the mutation tools share: their definition (`mutationToolBase`) and the call sequence after validation (
|
|
21
|
+
- `mutation-runner.ts` owns what the mutation tools share: their definition (`mutationToolBase`) and the call sequence after validation (`withFileMutationQueue`, the hand-off to the scheduler, and finalization). The `actionFusion` setting chooses the scheduler once at registration: `runAlone`, or Action Fusion's, which every mutation tool shares; the same setting adds `then_run` to the schema with its guideline and card. A tool supplies its schema, text, semantic checks, `run`, and renderers. The runner's per-call `publish` records the commit result before handing it to the tool. The publish call also records a `FileMutationError`'s publication if the commit throws. After a commit returns, every failure keeps its publication, including a no-op. `run` returns a tool-indexed `MutationOutcome`, the scheduler returns a `SettledMutation` (`alone`, or `fused` with its command facts), and one `finalizeMutation` call turns it into a result; nothing downstream reads publication or revisions back from result details. `runTextMutation` owns the read-modify-write for `edit`/`replace`, which supply only a `TextChange`.
|
|
22
22
|
- `file-read.ts` owns guarded byte acquisition and the mutation snapshot. It checks the opened handle and current path and hashes each chunk once. Mutation reads require the initial size of a regular file and reject premature EOF. Revision-only checks reuse one chunk buffer and retain only the digest. Editable snapshots retain filled chunks and join them for decoding when there is more than one. Text scans use Node's read-ahead to EOF, including virtual files that report zero size. `read` hands supported images to Pi's native read through Pi's image-detection API, delegates files containing NUL to it, and rejects all other invalid UTF-8; Pi owns those delegated reads. Delegated read uses Pi’s image-resize setting captured when the session starts, or on the first delegated read if the SDK reload skips `session_start`. Pi gives extensions no copy of the value it passed to its native read, so an SDK host that changes the setting after building the runtime and before the extension first reads it gets the new value in delegated reads and the old one in Pi's native read. The native MIME probe checks the target again at delegation because it can change after the dispatch probe.
|
|
23
23
|
- `file-revision.ts` defines a revision once as the SHA-256 hex of the exact bytes. `text-stream.ts` handles streaming text and returns the revision from `file-read.ts`.
|
|
24
24
|
- `file-commit.ts` publishes: no-op detection, a temp file in a sibling directory, then `link` (create) or `rename` (overwrite). It stages overwrites beside the resolved target and rechecks the requested path and target admission before renaming. It preserves existing file modes (a new file follows the umask) and syncs the directory on POSIX. A failure with a publication status to state throws `FileMutationError`; every other failure stays a plain `HashlineError`, reported as `NOT_PUBLISHED`. A commit intent is `create`, `overwrite`, or `update` (read-modify-write, the only one with a `baseRevision`); `planPublication` inspects the target once and returns the publish plan the rest of the commit follows, and the result states the freshness observed right after publication. It also owns freshness: the commit result's own, and `observeFreshness` for Fusion's later observations; only unknown freshness carries an observation error.
|
|
25
|
-
- `mutation-result.ts` owns final success/failure details and progress details. It builds diffs and finalizes each mutation from its tagged tool facts, commit, freshness, and command facts.
|
|
25
|
+
- `mutation-result.ts` owns final success/failure details and progress details. It builds diffs and finalizes each mutation from its tagged tool facts, commit, freshness, and command facts. On failure after a returned commit, `describeMutationFailure` wraps the original cause as `POST_PROCESS_FAILED`. It passes the recorded publication, known command status and first display error to `describeFailure`, which keeps those facts even when inspecting a thrown value fails. `failure-context.ts` turns anchor failures into a `HashlineError` with `failures` and bounded `candidateNeighborhoods`. The report layer bounds the `failures` list. `anchor-format.ts` owns the `LINE#HASH` syntax, its schema pattern, and row parsing.
|
|
26
26
|
- `mutation-diff.ts` keeps the Pi diff row format. Whole rows proven by copied spans delimit changed ranges. A BOM common to both snapshots stays with the file, so the first row's copied body can establish its identity independently of the BOM. When adding or removing a neighboring row changes the last line's terminator, a copied full body identifies the surviving row. jsdiff's `diffArrays` aligns each range under the line edit-distance budget. If the search exceeds the budget or leaves a proven row unmatched, the card preserves the proven match and shows the remaining original and replacement rows as blocks. Saved details carry the diff text.
|
|
27
27
|
|
|
28
28
|
## grep
|
|
@@ -50,7 +50,7 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
|
|
|
50
50
|
- `report-schema.ts` is the single definition of the result protocol: every report field in output order (each with one owning layer), its schema, audience, and model decision purpose, every error code with its facts schema and recovery (`next.default` plus named alternatives), and the success recovery order (`OUTCOME_NEXT`). `FACT_FIELDS` is the required declaration point; model omission is derived from its audience together with the call fields, so `report.ts` does not maintain a second field set. Checked report types retain their tool or error-code variant; absent fields remain readable as undefined. Types derive from it. Its closed wire schemas validate text-only reports, enforce legal tool names, and require code-specific facts.
|
|
51
51
|
- `report.ts` builds reports and owns their one model-facing serialization (`renderReport`: one JSON object, fields in schema order). Result text omits the call's own `tool`/`path` and TUI-only facts, which stay in `details.report`. `reportResult` appends a success report after the tool's payload only when the report states a model-visible fact or the result has no payload. When it appends a block, it records its zero-based position as `details.reportBlockIndex` for the TUI and session replay. After the execution-entry argument check, every tool runs inside `runTool`, which classifies a failure (`describeFailure`, structured `cause`, `next` from code and publication) and returns it as an `isError` result whose `details.report` the TUI renders. This module receives a mutation's failure facts from `mutation-result.ts` and does not depend on the commit layer.
|
|
52
52
|
- `reportBlockIndex` is present only when the success builder appends a report block. It belongs to the persisted TUI details format. Model-facing content, script output, and failure details use their own contracts. The [root replay contract](../../AGENTS.md#behavior-contracts) governs persisted format changes. Without a recorded index the success splitter leaves the content intact.
|
|
53
|
-
- `SCRIPT_OUTPUT_SCHEMAS` defines the full success facts for each tool. Producers derive their input types from it, so each mutation supplies `publication`, replace supplies `matches`, and grep supplies `matches` and `files`. The success wire schemas allow omitted fields when decoding reports. `reportResult` projects the complete facts into Pi's `structuredContent`, model payload, and report. Visibility flags carry no fact values. Counts already shown by grep's payload and a continuation already known from read's caller limit stay out of report text, its `next`, and `details.report`.
|
|
53
|
+
- `SCRIPT_OUTPUT_SCHEMAS` defines the full success facts for each tool. Producers derive their input types from it, so each mutation supplies `publication`, replace supplies `matches`, and grep supplies `matches` and `files`. The success wire schemas allow omitted fields when decoding reports. `reportResult` projects the complete facts into Pi's `structuredContent`, model payload, and report. Visibility flags carry no fact values. Counts already shown by grep's payload and a continuation already known from read's caller limit stay out of report text, its `next`, and `details.report`. The final session Bash text and image content blocks reach the model in order with native formatting, limits and truncation, without a Hashline field-budget pass; the separate report states the command's status. Scripts get `then_run.status` and native structured fields when supplied: `output` (raw stdout/stderr, possibly empty), `truncated`, optional `full_output_path`, `exit_code`, and `wall_time_seconds`. Permission blocks, timeouts, skipped commands, or overrides without a native structured result can have status alone, with diagnostics in content. The TUI retains native command card behavior. Scripts get the read or grep payload as `text`. A delegated image read passes Pi's image object through. A delegated read of a file containing NUL gives `{ text }` with Pi's output and no report facts.
|
|
54
54
|
- `render.ts` (`reportLines`) is the one TUI renderer of a report and holds the shared tool renderers. Render inputs admit partial details independently of the current execution result. Success renderers get the checked report and payload from `splitReport`. It strips a trailing text block only when its index equals `details.reportBlockIndex` and its text equals `renderReport` of the checked report. If a hook removes the report or changes its position or text without updating the corresponding details, the split preserves all content blocks and still returns any checked report facts. A hook that replaces a report with identical text at the same index can clear `reportBlockIndex` in its replacement details to mark that block as payload. Failure rendering uses `renderToolError` and `details.report`. The argument boundary throws before file access. A text-only argument rejection decodes from the final content block through `reportOf`. Both decoders check the same wire schema and require the originating call's tool. Only the text decoder fills in an omitted tool. Invalid text-only reports remain raw.
|
|
55
55
|
- A collapsed preview that hides rows ends with one marker in the form Pi's built-in cards use. Its expand hint comes from the render context's `keyHint`, because an imported `keyHint` can belong to another copy of Pi that does not see the host's keybindings. On a success card the report's facts follow the marker and stay visible when collapsed. `read` shows nothing when collapsed, as Pi's `read` does. A call line shows its path as Pi's cards do: the home directory as `~` (`shortenHomePath` in `path.ts`), and for `edit` and `replace` a link to the file where the terminal supports links (`formatHeaderPath`). `read` and `write` use Pi's own call renderers, and grep shortens without linking, as Pi's grep does. Pi exports neither path helper, so both are local. A card's body starts on the row under its call line, without the blank row Pi's built-in cards leave there. This difference from Pi is deliberate.
|
|
56
56
|
- A collapsed mutation card counts all diff rows for the header and overflow marker. Its preview passes only the visible rows and two rows of lookahead to Pi's `renderDiff`, which emits one row per input row and applies word highlighting only to a single removal followed by a single addition. The lookahead preserves that decision at the cutoff. Expanded cards pass the entire saved diff to Pi.
|
|
@@ -65,7 +65,7 @@ Pi integration. Cross-cutting contracts live in the root `AGENTS.md`; this file
|
|
|
65
65
|
|
|
66
66
|
## Action Fusion
|
|
67
67
|
|
|
68
|
-
`
|
|
68
|
+
`fusion-arguments.ts` keeps the concrete `then_run` fields in Pi's tool schema. Preparation rejects unknown caller fields. A rejected follow-up stays present across Pi's argument clone, carrying its diagnostic alongside an empty, non-executable command. A mutation hook can edit or replace the follow-up. The execution boundary checks that result without coercion. `action-fusion.ts` settles an invalid follow-up with the commit's actual publication and freshness, a failed command status and the diagnostic. For a valid follow-up it checks freshness against `publishedRevision`, then runs the command through the session's Bash with `ctx.executeTool("bash", ...)`, honoring overrides and the `tool_call` and `tool_result` hooks. The final session result decides the command's status, `terminate` passes on to the parent result, and a failed command does not roll back published files. Its own per-file queue wraps mutation and command around Pi's `withFileMutationQueue`; the module header explains the nesting. At Bash completion Fusion records `terminate` and each command fact as soon as Pi's result determines it. It reads indexed content into plain blocks once and gives progress subscribers a separate copy from the model payload. `native-bash.ts` takes the script fields from Pi's Bash output schema and shares the native definition with the card renderer. A finite `exit_code` establishes that the command exited even when the structured result is incomplete. Unreadable structured fields or display details are recorded in `progressError`. Model content, the known command outcome and the termination request survive those observer errors. A pre-run cancellation settles without reading output. Fusion progress derives from `ACTION_FUSION_PROGRESS_SCHEMA`. `fusion-card.ts` checks foreign card data, including restored session entries. The decoder verifies the progress schema and indexed content array before handing a result to Pi. Session entries receive a separate structured clone at each endpoint because `appendEntry` dispatches synchronously. Card snapshots copy the JSON representation of the fields Pi's Bash renderer reads: `fullOutputPath` and the `truncation` fields `truncated`, `truncatedBy`, `outputLines`, `totalLines`, and `maxBytes`. Other override details do not enter the card. It renders the separate mutation and command TUI cards (`withMutationStatus`, `registerFusionCards`) and derives a not-run reason from the same facts.
|
|
69
69
|
|
|
70
70
|
Fusion matches its nested Bash `tool_call` by parent ID inside the dispatch scope. Bash's first execution update fixes the displayed command and snapshots the hook-edited timeout for the countdown and final classification. For a silent override, Fusion reads the fallback timeout only for a final error with an execution duration and no numeric exit code. It checks for cancellation after timeout classification. Fusion reports `timeout` when Pi returns a final error with an execution duration, without a structured numeric exit code, and the final text matches or ends with Pi Bash's diagnostic for the observed timeout. Pi measures execution duration only for calls that ran. A silent override or result hook can change the shared input or final output, so this classification depends on them preserving the timeout and its diagnostic.
|
|
71
71
|
|
package/src/pi/action-fusion.ts
CHANGED
|
@@ -32,9 +32,11 @@ import type {
|
|
|
32
32
|
ExtensionToolContext,
|
|
33
33
|
ToolCallEvent,
|
|
34
34
|
} from "@earendil-works/pi-coding-agent";
|
|
35
|
-
import
|
|
35
|
+
import type { ThenRunInput } from "./fusion-arguments.ts";
|
|
36
|
+
import { MILLISECONDS_PER_SECOND, MAX_BASH_TIMEOUT_SECONDS } from "./fusion-arguments.ts";
|
|
36
37
|
import { observeFreshness, type FreshnessObservation } from "./file-commit.ts";
|
|
37
38
|
import { projectBashDetails } from "./fusion-card.ts";
|
|
39
|
+
import { snapshotBashOutput } from "./native-bash.ts";
|
|
38
40
|
import type {
|
|
39
41
|
CommandFacts,
|
|
40
42
|
MutationCommandFacts,
|
|
@@ -50,14 +52,8 @@ import type {
|
|
|
50
52
|
CommandResult,
|
|
51
53
|
CommandStatus,
|
|
52
54
|
Freshness,
|
|
53
|
-
MutationToolName,
|
|
54
55
|
} from "./report-schema.ts";
|
|
55
56
|
|
|
56
|
-
const MILLISECONDS_PER_SECOND = 1_000;
|
|
57
|
-
|
|
58
|
-
// Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
|
|
59
|
-
const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
|
|
60
|
-
|
|
61
57
|
// The one place the model is told when to use then_run; the tools' descriptions stay their own.
|
|
62
58
|
export const ACTION_FUSION_GUIDELINES = [
|
|
63
59
|
`Set then_run on edit, replace, or write for a check that can run right after that change. Use a separate bash call when the command requires approval, needs information from the tool's result, must wait for reload, or covers several changes; run that check once after all of them.${
|
|
@@ -70,43 +66,6 @@ export const ACTION_FUSION_GUIDELINES = [
|
|
|
70
66
|
|
|
71
67
|
type ProgressReporter = (progress: ActionFusionProgress) => void;
|
|
72
68
|
|
|
73
|
-
function createThenRunSchema(tool: MutationToolName) {
|
|
74
|
-
return Type.Optional(
|
|
75
|
-
Type.Object(
|
|
76
|
-
{
|
|
77
|
-
command: Type.String({ pattern: "\\S", description: "Bash command to run." }),
|
|
78
|
-
timeout: Type.Optional(
|
|
79
|
-
Type.Number({
|
|
80
|
-
exclusiveMinimum: 0,
|
|
81
|
-
maximum: MAX_BASH_TIMEOUT_SECONDS,
|
|
82
|
-
description: "Timeout in seconds; none when omitted.",
|
|
83
|
-
}),
|
|
84
|
-
),
|
|
85
|
-
},
|
|
86
|
-
{
|
|
87
|
-
description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
|
|
88
|
-
additionalProperties: false,
|
|
89
|
-
},
|
|
90
|
-
),
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
|
|
95
|
-
export function withThenRunSchema<P extends TProperties>(
|
|
96
|
-
schema: TObject<P>,
|
|
97
|
-
tool: MutationToolName,
|
|
98
|
-
actionFusion: boolean,
|
|
99
|
-
): TObject<P> | TObject<P & { then_run: ReturnType<typeof createThenRunSchema> }> {
|
|
100
|
-
return actionFusion
|
|
101
|
-
? Type.Object(
|
|
102
|
-
{ ...schema.properties, then_run: createThenRunSchema(tool) },
|
|
103
|
-
{ additionalProperties: false },
|
|
104
|
-
)
|
|
105
|
-
: schema;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
|
|
109
|
-
|
|
110
69
|
interface BashCallScope {
|
|
111
70
|
readonly toolCallId: string;
|
|
112
71
|
input?: BashToolCallEvent["input"] | Record<string, unknown>;
|
|
@@ -146,15 +105,6 @@ function bashTimeoutSeconds(timeout: unknown): number | undefined {
|
|
|
146
105
|
return timeout;
|
|
147
106
|
}
|
|
148
107
|
|
|
149
|
-
function hasNumericExitCode(structured: unknown): boolean {
|
|
150
|
-
return (
|
|
151
|
-
structured !== null &&
|
|
152
|
-
typeof structured === "object" &&
|
|
153
|
-
"exit_code" in structured &&
|
|
154
|
-
typeof structured.exit_code === "number"
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
108
|
/** Session listeners can replace array methods and block properties. Read indexed values once. */
|
|
159
109
|
function snapshotOutput(
|
|
160
110
|
source: CommandResult["content"],
|
|
@@ -184,7 +134,7 @@ function snapshotOutput(
|
|
|
184
134
|
recordObserverFailure(error);
|
|
185
135
|
}
|
|
186
136
|
}
|
|
187
|
-
return
|
|
137
|
+
return content;
|
|
188
138
|
}
|
|
189
139
|
|
|
190
140
|
/**
|
|
@@ -194,20 +144,20 @@ function snapshotOutput(
|
|
|
194
144
|
*/
|
|
195
145
|
function createBashCallCoordinator<TDetails extends object>({
|
|
196
146
|
toolCallId,
|
|
197
|
-
|
|
147
|
+
commandText,
|
|
198
148
|
onProgress,
|
|
199
149
|
onUpdate,
|
|
200
150
|
recordCommand,
|
|
201
151
|
}: {
|
|
202
152
|
toolCallId: string;
|
|
203
|
-
|
|
153
|
+
commandText: string;
|
|
204
154
|
onProgress: ProgressReporter;
|
|
205
155
|
onUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
|
|
206
156
|
recordCommand: (facts: MutationCommandFacts) => void;
|
|
207
157
|
}) {
|
|
208
158
|
const bashCall: BashCallScope = { toolCallId };
|
|
209
159
|
let mutationDetails: TDetails | undefined;
|
|
210
|
-
let displayedCommand =
|
|
160
|
+
let displayedCommand = commandText;
|
|
211
161
|
let commandResult: CommandResult | undefined;
|
|
212
162
|
let finalStatus: CommandStatus | undefined;
|
|
213
163
|
let launchTimeoutSeconds: number | undefined;
|
|
@@ -277,7 +227,16 @@ function createBashCallCoordinator<TDetails extends object>({
|
|
|
277
227
|
report("running", "unknown");
|
|
278
228
|
};
|
|
279
229
|
|
|
280
|
-
|
|
230
|
+
function failCommand(status: "failed" | "cancelled", message: string): CommandFacts {
|
|
231
|
+
recordStatus(status);
|
|
232
|
+
return snapshotCommand({ content: [{ type: "text", text: message }] }, status, undefined);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function runCommand(
|
|
236
|
+
thenRun: ThenRunInput,
|
|
237
|
+
signal: AbortSignal,
|
|
238
|
+
ctx: ExtensionToolContext,
|
|
239
|
+
): Promise<CommandFacts> {
|
|
281
240
|
let completion;
|
|
282
241
|
let hookInput;
|
|
283
242
|
try {
|
|
@@ -286,10 +245,7 @@ function createBashCallCoordinator<TDetails extends object>({
|
|
|
286
245
|
);
|
|
287
246
|
} catch (error) {
|
|
288
247
|
const status = signal.aborted ? "cancelled" : "failed";
|
|
289
|
-
|
|
290
|
-
const output = errorMessage(error);
|
|
291
|
-
commandResult = { content: [{ type: "text", text: output }] };
|
|
292
|
-
return { status, output };
|
|
248
|
+
return failCommand(status, errorMessage(error));
|
|
293
249
|
} finally {
|
|
294
250
|
hookInput = bashCall.input;
|
|
295
251
|
delete bashCall.input;
|
|
@@ -302,17 +258,18 @@ function createBashCallCoordinator<TDetails extends object>({
|
|
|
302
258
|
function snapshotCommand(
|
|
303
259
|
result: CommandResult,
|
|
304
260
|
status: Exclude<CommandStatus, "skipped">,
|
|
305
|
-
|
|
261
|
+
structured: ReturnType<typeof snapshotBashOutput>["structured"],
|
|
262
|
+
content = snapshotOutput(result.content, recordObserverFailure),
|
|
306
263
|
): CommandFacts {
|
|
307
|
-
|
|
308
|
-
commandResult = { content };
|
|
264
|
+
// Progress subscribers may mutate the card's blocks before the mutation is finalized.
|
|
265
|
+
commandResult = { content: content.map((block) => ({ ...block })) };
|
|
309
266
|
try {
|
|
310
267
|
const details = projectBashDetails(result.details);
|
|
311
|
-
if (details !== undefined) commandResult =
|
|
268
|
+
if (details !== undefined) commandResult.details = details;
|
|
312
269
|
} catch (error) {
|
|
313
270
|
recordObserverFailure(error);
|
|
314
271
|
}
|
|
315
|
-
return { status,
|
|
272
|
+
return { script: { status, ...structured }, content };
|
|
316
273
|
}
|
|
317
274
|
|
|
318
275
|
function readCompletion(
|
|
@@ -325,28 +282,30 @@ function createBashCallCoordinator<TDetails extends object>({
|
|
|
325
282
|
if (!isError) recordStatus("succeeded");
|
|
326
283
|
const terminate = result.terminate;
|
|
327
284
|
if (typeof terminate === "boolean") recordCommand({ terminate });
|
|
328
|
-
|
|
285
|
+
const { exited, structured } = snapshotBashOutput(result, recordObserverFailure);
|
|
286
|
+
if (!isError) return snapshotCommand(result, "succeeded", structured);
|
|
329
287
|
|
|
330
288
|
const finishError = (
|
|
331
289
|
status: "failed" | "timeout" | "cancelled",
|
|
332
290
|
snapshot?: ReturnType<typeof snapshotOutput>,
|
|
333
291
|
): CommandFacts => {
|
|
334
292
|
recordStatus(status);
|
|
335
|
-
return snapshotCommand(result, status, snapshot);
|
|
293
|
+
return snapshotCommand(result, status, structured, snapshot);
|
|
336
294
|
};
|
|
337
295
|
|
|
338
|
-
if (
|
|
296
|
+
if (exited) return finishError("failed");
|
|
339
297
|
if (durationMs === undefined) {
|
|
340
298
|
if (!signal.aborted) return finishError("failed");
|
|
341
299
|
recordStatus("cancelled");
|
|
342
300
|
commandResult = undefined;
|
|
343
|
-
return { status: "cancelled" };
|
|
301
|
+
return { script: { status: "cancelled" }, content: [] };
|
|
344
302
|
}
|
|
345
303
|
const timeout = launchTimeoutSeconds ?? bashTimeoutSeconds(hookInput?.timeout);
|
|
346
304
|
if (timeout === undefined) return finishError(signal.aborted ? "cancelled" : "failed");
|
|
347
305
|
const snapshot = snapshotOutput(result.content, recordObserverFailure);
|
|
306
|
+
const text = contentText(snapshot);
|
|
348
307
|
const diagnostic = `Command timed out after ${timeout} seconds`;
|
|
349
|
-
if (
|
|
308
|
+
if (text === diagnostic || text.endsWith(`\n${diagnostic}`))
|
|
350
309
|
return finishError("timeout", snapshot);
|
|
351
310
|
return finishError(signal.aborted ? "cancelled" : "failed", snapshot);
|
|
352
311
|
}
|
|
@@ -354,6 +313,7 @@ function createBashCallCoordinator<TDetails extends object>({
|
|
|
354
313
|
return {
|
|
355
314
|
report,
|
|
356
315
|
runCommand,
|
|
316
|
+
failCommand,
|
|
357
317
|
reportCompletion() {
|
|
358
318
|
if (finalStatus !== undefined) report(finalStatus, "unknown");
|
|
359
319
|
},
|
|
@@ -425,7 +385,7 @@ export function createActionFusionScheduler(onProgress: ProgressReporter): Mutat
|
|
|
425
385
|
|
|
426
386
|
const progress = createBashCallCoordinator({
|
|
427
387
|
toolCallId,
|
|
428
|
-
thenRun,
|
|
388
|
+
commandText: "command" in thenRun ? thenRun.command : thenRun.commandText,
|
|
429
389
|
onProgress,
|
|
430
390
|
onUpdate,
|
|
431
391
|
recordCommand,
|
|
@@ -447,7 +407,7 @@ export function createActionFusionScheduler(onProgress: ProgressReporter): Mutat
|
|
|
447
407
|
const { publishedRevision } = outcome.commit;
|
|
448
408
|
progress.report("waiting", "unknown");
|
|
449
409
|
const settle = (observation: FreshnessObservation, command: CommandFacts) => {
|
|
450
|
-
progress.report(command.status, observation.freshness);
|
|
410
|
+
progress.report(command.script.status, observation.freshness);
|
|
451
411
|
return {
|
|
452
412
|
kind: "fused" as const,
|
|
453
413
|
outcome,
|
|
@@ -456,6 +416,9 @@ export function createActionFusionScheduler(onProgress: ProgressReporter): Mutat
|
|
|
456
416
|
};
|
|
457
417
|
};
|
|
458
418
|
|
|
419
|
+
if ("error" in thenRun)
|
|
420
|
+
return settle(outcome.commit, progress.failCommand("failed", thenRun.error));
|
|
421
|
+
|
|
459
422
|
// A completed mutation remains successful; the command is only started on a fresh target.
|
|
460
423
|
const before = await observeFreshness(absolutePath, publishedRevision, "before-command");
|
|
461
424
|
const beforeStatus = signal.aborted
|
|
@@ -465,14 +428,14 @@ export function createActionFusionScheduler(onProgress: ProgressReporter): Mutat
|
|
|
465
428
|
: undefined;
|
|
466
429
|
if (beforeStatus !== undefined) {
|
|
467
430
|
recordCommand({ status: beforeStatus });
|
|
468
|
-
return settle(before, { status: beforeStatus });
|
|
431
|
+
return settle(before, { script: { status: beforeStatus }, content: [] });
|
|
469
432
|
}
|
|
470
433
|
|
|
471
434
|
progress.report("running", "unchanged");
|
|
472
435
|
const scope = { active: true };
|
|
473
436
|
try {
|
|
474
437
|
const command = await commandScope
|
|
475
|
-
.run(scope, () => progress.runCommand(signal, ctx))
|
|
438
|
+
.run(scope, () => progress.runCommand(thenRun, signal, ctx))
|
|
476
439
|
.finally(() => {
|
|
477
440
|
scope.active = false;
|
|
478
441
|
});
|
|
@@ -136,6 +136,30 @@ function firstArrayIssue(schema: TSchema, value: unknown, path = ""): ArgumentIs
|
|
|
136
136
|
return undefined;
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
function withArgumentError<Value>(
|
|
140
|
+
operation: () => Value,
|
|
141
|
+
budgets: OutputBudgetProvider,
|
|
142
|
+
field = "$",
|
|
143
|
+
): Value {
|
|
144
|
+
try {
|
|
145
|
+
return operation();
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw new Error(
|
|
148
|
+
formatArgumentError([{ field, reason: errorMessage(error) }], false, budgets()),
|
|
149
|
+
{ cause: error },
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Snapshot enumerable call data under the diagnostic budget of the owning operation. */
|
|
155
|
+
export function cloneArguments<Value>(
|
|
156
|
+
args: Value,
|
|
157
|
+
budgets: OutputBudgetProvider,
|
|
158
|
+
field = "$",
|
|
159
|
+
): Value {
|
|
160
|
+
return withArgumentError(() => structuredClone(args), budgets, field);
|
|
161
|
+
}
|
|
162
|
+
|
|
139
163
|
export function createArgumentBoundary<T extends TObject, Parsed>(
|
|
140
164
|
parameters: T,
|
|
141
165
|
cwd: string,
|
|
@@ -144,26 +168,15 @@ export function createArgumentBoundary<T extends TObject, Parsed>(
|
|
|
144
168
|
) {
|
|
145
169
|
const validator = compile(parameters, COMPILE_OPTIONS);
|
|
146
170
|
|
|
147
|
-
function withArgumentError<Value>(operation: () => Value): Value {
|
|
148
|
-
try {
|
|
149
|
-
return operation();
|
|
150
|
-
} catch (error) {
|
|
151
|
-
throw new Error(
|
|
152
|
-
formatArgumentError([{ field: "$", reason: errorMessage(error) }], false, budgets()),
|
|
153
|
-
{ cause: error },
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
171
|
function snapshot<Value>(args: Value): Value {
|
|
159
|
-
const copy =
|
|
172
|
+
const copy = cloneArguments(args, budgets);
|
|
160
173
|
const issue = firstArrayIssue(parameters, copy);
|
|
161
174
|
if (issue) throw new Error(formatArgumentError([issue], false, budgets()));
|
|
162
175
|
return copy;
|
|
163
176
|
}
|
|
164
177
|
|
|
165
178
|
function verdict(checked: unknown) {
|
|
166
|
-
const schemaFailed = !withArgumentError(() => validator.check(checked));
|
|
179
|
+
const schemaFailed = !withArgumentError(() => validator.check(checked), budgets);
|
|
167
180
|
const issues: ArgumentIssue[] = [];
|
|
168
181
|
const report: ReportArgumentIssue = (field, reason, fix) => {
|
|
169
182
|
issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
|
|
@@ -184,20 +197,21 @@ export function createArgumentBoundary<T extends TObject, Parsed>(
|
|
|
184
197
|
return {
|
|
185
198
|
prepareArguments(args: unknown): Static<T> {
|
|
186
199
|
const raw = snapshot(args);
|
|
187
|
-
verdict(withArgumentError(() => validator.coerce(raw)));
|
|
200
|
+
verdict(withArgumentError(() => validator.coerce(raw), budgets));
|
|
188
201
|
// Coercion is copy-on-write. Pi applies it to this snapshot before passing args to hooks.
|
|
189
202
|
return raw as Static<T>;
|
|
190
203
|
},
|
|
191
204
|
// A tool_call hook can retain and mutate the validated arguments before or during execution.
|
|
192
205
|
// The tool consumes its own checked snapshot of the canonical arguments the last hook left.
|
|
193
|
-
afterHooks
|
|
206
|
+
afterHooks(args: unknown) {
|
|
194
207
|
const checked = snapshot(args);
|
|
195
208
|
const { build, locals } = verdict(checked);
|
|
196
209
|
const paths: ResolvedArgumentPath[] = locals.map(({ spelling, local }) => ({
|
|
197
210
|
absolutePath: resolve(cwd, local),
|
|
198
211
|
spelling,
|
|
199
212
|
}));
|
|
200
|
-
|
|
213
|
+
// The schema and semantic checks above validate this owned execution snapshot.
|
|
214
|
+
return { args: checked as Static<T>, parsed: build(), paths };
|
|
201
215
|
},
|
|
202
216
|
};
|
|
203
217
|
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/** Independent argument checks for the file operation and its optional Bash command. */
|
|
2
|
+
import { isProxy } from "node:util/types";
|
|
3
|
+
import { Type, type Static, type TObject, type TProperties } from "typebox";
|
|
4
|
+
import { errorMessage } from "../core/errors.ts";
|
|
5
|
+
import {
|
|
6
|
+
cloneArguments,
|
|
7
|
+
createArgumentBoundary,
|
|
8
|
+
noArgumentProduct,
|
|
9
|
+
type CheckArguments,
|
|
10
|
+
} from "./argument-validation.ts";
|
|
11
|
+
import { reportOf } from "./report.ts";
|
|
12
|
+
import type { OutputBudgetProvider } from "./budgets.ts";
|
|
13
|
+
import type { MutationToolName } from "./report-schema.ts";
|
|
14
|
+
|
|
15
|
+
export const MILLISECONDS_PER_SECOND = 1_000;
|
|
16
|
+
// Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
|
|
17
|
+
export const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
|
|
18
|
+
|
|
19
|
+
const command = Type.String({ description: "Bash command to run." });
|
|
20
|
+
const timeout = Type.Optional(
|
|
21
|
+
Type.Number({
|
|
22
|
+
exclusiveMinimum: 0,
|
|
23
|
+
maximum: MAX_BASH_TIMEOUT_SECONDS,
|
|
24
|
+
description: "Timeout in seconds; none when omitted.",
|
|
25
|
+
}),
|
|
26
|
+
);
|
|
27
|
+
const commandArguments = Type.Object(
|
|
28
|
+
{
|
|
29
|
+
then_run: Type.Optional(
|
|
30
|
+
Type.Object(
|
|
31
|
+
{
|
|
32
|
+
command: Type.String({ ...command, pattern: "\\S" }),
|
|
33
|
+
timeout,
|
|
34
|
+
},
|
|
35
|
+
{ additionalProperties: false },
|
|
36
|
+
),
|
|
37
|
+
),
|
|
38
|
+
},
|
|
39
|
+
{ additionalProperties: false },
|
|
40
|
+
);
|
|
41
|
+
export type ThenRunInput = NonNullable<Static<typeof commandArguments>["then_run"]>;
|
|
42
|
+
export type ThenRunRequest =
|
|
43
|
+
| ThenRunInput
|
|
44
|
+
| { readonly commandText: string; readonly error: string };
|
|
45
|
+
|
|
46
|
+
// Pi clones and validates prepared arguments before hooks. Keep a rejected request present so a
|
|
47
|
+
// hook supplying defaults for an absent command cannot start Bash. Its empty command also fails
|
|
48
|
+
// the execution schema on its own. The diagnostic is never a shell argument.
|
|
49
|
+
const REJECTED = "__hashlineThenRunError";
|
|
50
|
+
|
|
51
|
+
function rawCommandText(value: unknown): string {
|
|
52
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return "";
|
|
53
|
+
const text: unknown = Reflect.get(value, "command");
|
|
54
|
+
return typeof text === "string" ? text : "";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Let structuredClone observe fields in their original order and with the original receiver. */
|
|
58
|
+
function mapFollowUp(
|
|
59
|
+
input: unknown,
|
|
60
|
+
visit: (read: () => { then_run: unknown }) => unknown,
|
|
61
|
+
budgets: OutputBudgetProvider,
|
|
62
|
+
): unknown {
|
|
63
|
+
if (
|
|
64
|
+
!input ||
|
|
65
|
+
typeof input !== "object" ||
|
|
66
|
+
Array.isArray(input) ||
|
|
67
|
+
isProxy(input) ||
|
|
68
|
+
!Object.prototype.propertyIsEnumerable.call(input, "then_run")
|
|
69
|
+
)
|
|
70
|
+
return input;
|
|
71
|
+
const proto: unknown = Object.getPrototypeOf(input);
|
|
72
|
+
if (proto !== null && proto !== Object.prototype) {
|
|
73
|
+
// Built-ins such as Date drop custom properties when cloned. Class instances become records.
|
|
74
|
+
return mapFollowUp(cloneArguments(input, budgets), visit, budgets);
|
|
75
|
+
}
|
|
76
|
+
const view = {};
|
|
77
|
+
for (const key of Object.keys(input)) {
|
|
78
|
+
Object.defineProperty(view, key, {
|
|
79
|
+
enumerable: true,
|
|
80
|
+
get:
|
|
81
|
+
key === "then_run"
|
|
82
|
+
? () =>
|
|
83
|
+
visit(() =>
|
|
84
|
+
cloneArguments(
|
|
85
|
+
{
|
|
86
|
+
get then_run() {
|
|
87
|
+
return Reflect.get(input, key);
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
budgets,
|
|
91
|
+
"then_run",
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
: () => Reflect.get(input, key),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return view;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function createMutationArgumentBoundary<P extends TProperties, Parsed>(
|
|
101
|
+
schema: TObject<P>,
|
|
102
|
+
tool: MutationToolName,
|
|
103
|
+
actionFusion: boolean,
|
|
104
|
+
cwd: string,
|
|
105
|
+
budgets: OutputBudgetProvider,
|
|
106
|
+
check: CheckArguments<Parsed>,
|
|
107
|
+
) {
|
|
108
|
+
if (!actionFusion) {
|
|
109
|
+
const file = createArgumentBoundary(schema, cwd, budgets, check);
|
|
110
|
+
return {
|
|
111
|
+
parameters: schema,
|
|
112
|
+
prepareArguments: file.prepareArguments,
|
|
113
|
+
afterHooks: (input: unknown) => ({ ...file.afterHooks(input), thenRun: undefined }),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const parameters = Type.Object(
|
|
117
|
+
{
|
|
118
|
+
...schema.properties,
|
|
119
|
+
then_run: Type.Optional(
|
|
120
|
+
Type.Object(
|
|
121
|
+
{ command, timeout },
|
|
122
|
+
{
|
|
123
|
+
description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
|
|
124
|
+
},
|
|
125
|
+
),
|
|
126
|
+
),
|
|
127
|
+
},
|
|
128
|
+
{ additionalProperties: false },
|
|
129
|
+
);
|
|
130
|
+
const file = createArgumentBoundary(
|
|
131
|
+
Type.Object(
|
|
132
|
+
{ ...schema.properties, then_run: Type.Optional(Type.Unknown()) },
|
|
133
|
+
{ additionalProperties: false },
|
|
134
|
+
),
|
|
135
|
+
cwd,
|
|
136
|
+
budgets,
|
|
137
|
+
check,
|
|
138
|
+
);
|
|
139
|
+
const bash = createArgumentBoundary(commandArguments, cwd, budgets, () => noArgumentProduct);
|
|
140
|
+
return {
|
|
141
|
+
parameters,
|
|
142
|
+
prepareArguments(input: unknown): Static<typeof parameters> {
|
|
143
|
+
const prepared = file.prepareArguments(
|
|
144
|
+
mapFollowUp(
|
|
145
|
+
input,
|
|
146
|
+
(read) => {
|
|
147
|
+
let commandText = "";
|
|
148
|
+
try {
|
|
149
|
+
const snapshot = read();
|
|
150
|
+
commandText = rawCommandText(snapshot.then_run);
|
|
151
|
+
return bash.prepareArguments(snapshot).then_run;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
return {
|
|
154
|
+
command: "",
|
|
155
|
+
[REJECTED]: { commandText, error: errorMessage(error) },
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
budgets,
|
|
160
|
+
),
|
|
161
|
+
);
|
|
162
|
+
// Pi applies the registered schema's coercion to the same raw fields after preparation.
|
|
163
|
+
return prepared as Static<typeof parameters>;
|
|
164
|
+
},
|
|
165
|
+
afterHooks(input: unknown) {
|
|
166
|
+
let thenRun: ThenRunRequest | undefined;
|
|
167
|
+
const mutation = file.afterHooks(
|
|
168
|
+
mapFollowUp(
|
|
169
|
+
input,
|
|
170
|
+
(read) => {
|
|
171
|
+
let commandText = "";
|
|
172
|
+
try {
|
|
173
|
+
const snapshot = read();
|
|
174
|
+
const value = snapshot.then_run;
|
|
175
|
+
commandText = rawCommandText(value);
|
|
176
|
+
if (value && typeof value === "object" && Object.hasOwn(value, REJECTED)) {
|
|
177
|
+
const marker: unknown = Reflect.get(value, REJECTED);
|
|
178
|
+
const diagnostic: unknown =
|
|
179
|
+
marker && typeof marker === "object" ? Reflect.get(marker, "error") : undefined;
|
|
180
|
+
const rejectedCommand: unknown =
|
|
181
|
+
marker && typeof marker === "object"
|
|
182
|
+
? Reflect.get(marker, "commandText")
|
|
183
|
+
: undefined;
|
|
184
|
+
const rejected =
|
|
185
|
+
typeof rejectedCommand === "string" &&
|
|
186
|
+
typeof diagnostic === "string" &&
|
|
187
|
+
Buffer.byteLength(diagnostic) <= budgets().blockBytes &&
|
|
188
|
+
reportOf({ content: [{ type: "text", text: diagnostic }] }, tool)?.error ===
|
|
189
|
+
"INVALID_ARGUMENTS";
|
|
190
|
+
if (
|
|
191
|
+
rejected &&
|
|
192
|
+
Object.keys(value).length === 2 &&
|
|
193
|
+
Reflect.get(value, "command") === ""
|
|
194
|
+
) {
|
|
195
|
+
thenRun = { commandText: rejectedCommand, error: diagnostic };
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
if (rejected) Reflect.deleteProperty(value, REJECTED);
|
|
199
|
+
}
|
|
200
|
+
thenRun = bash.afterHooks(snapshot).args.then_run;
|
|
201
|
+
} catch (error) {
|
|
202
|
+
thenRun = { commandText, error: errorMessage(error) };
|
|
203
|
+
}
|
|
204
|
+
return undefined;
|
|
205
|
+
},
|
|
206
|
+
budgets,
|
|
207
|
+
),
|
|
208
|
+
);
|
|
209
|
+
// TypeBox cannot infer the base mapped type after removing the independently checked field.
|
|
210
|
+
Reflect.deleteProperty(mutation.args, "then_run");
|
|
211
|
+
return { ...mutation, args: mutation.args as Static<typeof schema>, thenRun };
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
package/src/pi/fusion-card.ts
CHANGED
|
@@ -13,11 +13,7 @@ import type {
|
|
|
13
13
|
ToolDefinition,
|
|
14
14
|
ToolRenderers,
|
|
15
15
|
} from "@earendil-works/pi-coding-agent";
|
|
16
|
-
import {
|
|
17
|
-
createBashToolDefinition,
|
|
18
|
-
SettingsManager,
|
|
19
|
-
ToolExecutionComponent,
|
|
20
|
-
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { SettingsManager, ToolExecutionComponent } from "@earendil-works/pi-coding-agent";
|
|
21
17
|
import {
|
|
22
18
|
Box,
|
|
23
19
|
Container,
|
|
@@ -29,6 +25,7 @@ import {
|
|
|
29
25
|
import type { TSchema } from "typebox";
|
|
30
26
|
import { Value } from "typebox/value";
|
|
31
27
|
import { ACTION_FUSION_PROGRESS_SCHEMA, type ActionFusionProgress } from "./report-schema.ts";
|
|
28
|
+
import { nativeBash } from "./native-bash.ts";
|
|
32
29
|
import type { MutationRenderState } from "./render.ts";
|
|
33
30
|
import type { ToolGuidelines } from "./schema.ts";
|
|
34
31
|
|
|
@@ -158,7 +155,6 @@ class CommandEntryComponent extends ToolExecutionComponent {
|
|
|
158
155
|
/** Render one durable transcript card per fused command without adding model context. */
|
|
159
156
|
export function registerFusionCards(pi: ExtensionAPI) {
|
|
160
157
|
let currentCwd = process.cwd();
|
|
161
|
-
const bash = createBashToolDefinition(process.cwd());
|
|
162
158
|
const states = new Map<string, CommandCardData>();
|
|
163
159
|
const active = new Set<string>();
|
|
164
160
|
const cards = new Map<string, CommandEntryComponent>();
|
|
@@ -233,7 +229,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
233
229
|
statusText.setText(
|
|
234
230
|
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
|
|
235
231
|
);
|
|
236
|
-
call =
|
|
232
|
+
call = nativeBash.renderCall!(args, theme, { ...context, args, lastComponent: call });
|
|
237
233
|
box.clear();
|
|
238
234
|
box.addChild(statusText);
|
|
239
235
|
box.addChild(call);
|
|
@@ -244,7 +240,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
244
240
|
renderResult(value, options, theme, context) {
|
|
245
241
|
// Every command that ran or failed to start has a result; waiting and skipped ones do not.
|
|
246
242
|
if (current().result) {
|
|
247
|
-
result =
|
|
243
|
+
result = nativeBash.renderResult!(value, options, theme, {
|
|
248
244
|
...context,
|
|
249
245
|
args: { command: current().commandText, timeout: current().timing?.timeoutSeconds },
|
|
250
246
|
lastComponent: result,
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
8
8
|
import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
9
9
|
import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import type {
|
|
10
|
+
import type { ThenRunRequest } from "./fusion-arguments.ts";
|
|
11
11
|
import type { CommitResult, FreshnessObservation } from "./file-commit.ts";
|
|
12
12
|
import { generateRangeDiff } from "./mutation-diff.ts";
|
|
13
13
|
import { displayCarriageReturns } from "./anchor-format.ts";
|
|
@@ -15,12 +15,14 @@ import { HashlineError } from "../core/errors.ts";
|
|
|
15
15
|
import type { CopiedSpan } from "../core/copy-span.ts";
|
|
16
16
|
import type {
|
|
17
17
|
ActionFusionProgress,
|
|
18
|
+
CommandResult,
|
|
18
19
|
CommandStatus,
|
|
19
20
|
FailureReport,
|
|
20
21
|
MutationToolName,
|
|
21
22
|
PublicationStatus,
|
|
22
23
|
ReportTool,
|
|
23
24
|
MutationFacts,
|
|
25
|
+
SuccessFacts,
|
|
24
26
|
SuccessReport,
|
|
25
27
|
} from "./report-schema.ts";
|
|
26
28
|
import {
|
|
@@ -29,7 +31,7 @@ import {
|
|
|
29
31
|
type FailureContext,
|
|
30
32
|
type ReportDetails,
|
|
31
33
|
} from "./report.ts";
|
|
32
|
-
import {
|
|
34
|
+
import { describeThrown } from "./report-cause.ts";
|
|
33
35
|
import type { OutputBudgets } from "./budgets.ts";
|
|
34
36
|
|
|
35
37
|
/** Final success carries tool details; final failure carries only its report; neither carries progress. */
|
|
@@ -64,14 +66,11 @@ interface ObserverFailure {
|
|
|
64
66
|
readonly error: unknown;
|
|
65
67
|
}
|
|
66
68
|
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
export type CommandFacts =
|
|
73
|
-
| { readonly status: Extract<CommandStatus, "skipped" | "cancelled">; readonly output?: never }
|
|
74
|
-
| { readonly status: Exclude<CommandStatus, "skipped">; readonly output: string };
|
|
69
|
+
/** Bash's model-facing blocks and the script outcome for this follow-up. */
|
|
70
|
+
export interface CommandFacts {
|
|
71
|
+
readonly content: CommandResult["content"];
|
|
72
|
+
readonly script: NonNullable<SuccessFacts<MutationToolName>["then_run"]>;
|
|
73
|
+
}
|
|
75
74
|
|
|
76
75
|
/**
|
|
77
76
|
* A completed mutation. A call without then_run settles alone, and its commit result states its
|
|
@@ -100,7 +99,7 @@ export interface MutationCall<TDetails, TTool extends MutationToolName> {
|
|
|
100
99
|
readonly toolCallId: string;
|
|
101
100
|
readonly absolutePath: string;
|
|
102
101
|
/** The model's optional follow-up command; only Action Fusion's schema admits it. */
|
|
103
|
-
readonly thenRun:
|
|
102
|
+
readonly thenRun: ThenRunRequest | undefined;
|
|
104
103
|
readonly mutate: () => Promise<MutationOutcome<TDetails, TTool>>;
|
|
105
104
|
readonly signal: AbortSignal;
|
|
106
105
|
readonly ctx: ExtensionToolContext;
|
|
@@ -140,8 +139,8 @@ export function describeMutationFailure(
|
|
|
140
139
|
|
|
141
140
|
/**
|
|
142
141
|
* Build the mutation result from commit, freshness, and command facts; the TUI uses its diff
|
|
143
|
-
* details.
|
|
144
|
-
*
|
|
142
|
+
* details. The model receives Bash content before the status report. Scripts receive the
|
|
143
|
+
* follow-up status and Bash's structured fields in `then_run`.
|
|
145
144
|
*/
|
|
146
145
|
export function finalizeMutation<TDetails extends object>(
|
|
147
146
|
path: string,
|
|
@@ -152,7 +151,6 @@ export function finalizeMutation<TDetails extends object>(
|
|
|
152
151
|
const { commit, details, facts } = settled.outcome;
|
|
153
152
|
const observation: FreshnessObservation = settled.kind === "alone" ? commit : settled.observation;
|
|
154
153
|
const command = settled.kind === "fused" ? settled.command : undefined;
|
|
155
|
-
const output = command?.output && boundedText(command.output, budget.fieldBytes);
|
|
156
154
|
return reportResult(
|
|
157
155
|
{
|
|
158
156
|
...facts,
|
|
@@ -163,10 +161,10 @@ export function finalizeMutation<TDetails extends object>(
|
|
|
163
161
|
observation.freshness === "unknown"
|
|
164
162
|
? describeThrown(observation.error, budget.fieldBytes)
|
|
165
163
|
: undefined,
|
|
166
|
-
then_run: command
|
|
164
|
+
then_run: command?.script,
|
|
167
165
|
progressError: observerFailure(progressFailure, budget),
|
|
168
166
|
},
|
|
169
|
-
[],
|
|
167
|
+
command?.content ?? [],
|
|
170
168
|
budget,
|
|
171
169
|
{ details },
|
|
172
170
|
);
|
|
@@ -7,8 +7,7 @@
|
|
|
7
7
|
* semantic checks, and `run`, and adds its own renderers.
|
|
8
8
|
*
|
|
9
9
|
* Owns the sequencing every mutation tool must keep identical once Pi has
|
|
10
|
-
* checked the arguments:
|
|
11
|
-
* the shared file mutation queue, the hand-off to Action Fusion, and
|
|
10
|
+
* checked the arguments: the shared file mutation queue, the hand-off to Action Fusion, and
|
|
12
11
|
* finalization. Each tool returns a typed `MutationOutcome` (commit facts,
|
|
13
12
|
* details, outcome facts); Action Fusion returns facts too, and this module's
|
|
14
13
|
* single `finalizeMutation` call turns them into the result, so nothing
|
|
@@ -26,8 +25,9 @@
|
|
|
26
25
|
import { withFileMutationQueue, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
|
|
27
26
|
import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
28
27
|
import type { Static, TObject, TProperties } from "typebox";
|
|
29
|
-
import { ACTION_FUSION_GUIDELINES
|
|
30
|
-
import {
|
|
28
|
+
import { ACTION_FUSION_GUIDELINES } from "./action-fusion.ts";
|
|
29
|
+
import type { CheckArguments } from "./argument-validation.ts";
|
|
30
|
+
import { createMutationArgumentBoundary } from "./fusion-arguments.ts";
|
|
31
31
|
import {
|
|
32
32
|
SCRIPT_OUTPUT_SCHEMAS,
|
|
33
33
|
type MutationFacts,
|
|
@@ -81,9 +81,6 @@ export interface MutationTarget {
|
|
|
81
81
|
readonly budget: OutputBudgets;
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
/** A mutation tool's own parameters; `execute` separates then_run. */
|
|
85
|
-
type MutationParams<P extends TProperties> = Static<TObject<P>> & { readonly path: string };
|
|
86
|
-
|
|
87
84
|
/** What a mutation tool supplies to the shared definition; renderers stay with the tool. */
|
|
88
85
|
interface MutationToolSpec<P extends TProperties, TDetails, TTool extends MutationToolName, Parsed>
|
|
89
86
|
extends MutationToolEnvironment {
|
|
@@ -97,7 +94,7 @@ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends Mutati
|
|
|
97
94
|
readonly check: CheckArguments<Parsed>;
|
|
98
95
|
/** Perform the mutation. Runs inside the file mutation queue. */
|
|
99
96
|
run(
|
|
100
|
-
params:
|
|
97
|
+
params: Static<TObject<P>>,
|
|
101
98
|
target: MutationTarget,
|
|
102
99
|
parsed: NoInfer<Parsed>,
|
|
103
100
|
): Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
|
|
@@ -105,9 +102,9 @@ interface MutationToolSpec<P extends TProperties, TDetails, TTool extends Mutati
|
|
|
105
102
|
|
|
106
103
|
/**
|
|
107
104
|
* The definition every mutation tool shares. Action Fusion adds then_run to the
|
|
108
|
-
* schema and guidelines only when it is on
|
|
109
|
-
*
|
|
110
|
-
*
|
|
105
|
+
* schema and guidelines only when it is on. The argument boundary separates
|
|
106
|
+
* the file and follow-up verdicts. Execution queues and publishes the file
|
|
107
|
+
* operation before settling the follow-up.
|
|
111
108
|
*/
|
|
112
109
|
export function mutationToolBase<
|
|
113
110
|
P extends TProperties,
|
|
@@ -117,8 +114,14 @@ export function mutationToolBase<
|
|
|
117
114
|
>(spec: MutationToolSpec<P, TDetails, TTool, Parsed>) {
|
|
118
115
|
const { tool, cwd, schema, schedule, budgets } = spec;
|
|
119
116
|
const { actionFusion } = spec.config;
|
|
120
|
-
const
|
|
121
|
-
|
|
117
|
+
const boundary = createMutationArgumentBoundary(
|
|
118
|
+
schema,
|
|
119
|
+
tool,
|
|
120
|
+
actionFusion,
|
|
121
|
+
cwd,
|
|
122
|
+
budgets,
|
|
123
|
+
spec.check,
|
|
124
|
+
);
|
|
122
125
|
return {
|
|
123
126
|
name: tool,
|
|
124
127
|
label: tool,
|
|
@@ -128,14 +131,14 @@ export function mutationToolBase<
|
|
|
128
131
|
...(spec.promptGuidelines ?? []),
|
|
129
132
|
...(actionFusion ? ACTION_FUSION_GUIDELINES : []),
|
|
130
133
|
],
|
|
131
|
-
parameters,
|
|
134
|
+
parameters: boundary.parameters,
|
|
132
135
|
outputSchema: SCRIPT_OUTPUT_SCHEMAS[tool],
|
|
133
136
|
prepareArguments: boundary.prepareArguments,
|
|
134
137
|
constrainedSampling: STRICT_SAMPLING,
|
|
135
138
|
renderShell: "default" as const,
|
|
136
139
|
async execute(
|
|
137
140
|
toolCallId: string,
|
|
138
|
-
params:
|
|
141
|
+
params: Static<typeof boundary.parameters>,
|
|
139
142
|
piSignal: AbortSignal | undefined,
|
|
140
143
|
piOnUpdate: AgentToolUpdateCallback<MutationResultDetails<TDetails>> | undefined,
|
|
141
144
|
ctx: ExtensionToolContext,
|
|
@@ -144,12 +147,11 @@ export function mutationToolBase<
|
|
|
144
147
|
// Pi's agent loop always supplies a callback; a direct call without one has no display.
|
|
145
148
|
const onUpdate = piOnUpdate ?? (() => {});
|
|
146
149
|
const {
|
|
147
|
-
args,
|
|
150
|
+
args: mutationParams,
|
|
148
151
|
parsed,
|
|
149
|
-
paths: [{ absolutePath }],
|
|
152
|
+
paths: [{ absolutePath, spelling: displayPath }],
|
|
153
|
+
thenRun,
|
|
150
154
|
} = boundary.afterHooks(params);
|
|
151
|
-
const { then_run, ...mutationParams } = args;
|
|
152
|
-
const displayPath = mutationParams.path;
|
|
153
155
|
const budget = budgets();
|
|
154
156
|
let commit: CommitResult | undefined;
|
|
155
157
|
let failedPublication: PublicationStatus | undefined;
|
|
@@ -177,7 +179,7 @@ export function mutationToolBase<
|
|
|
177
179
|
const settled = await schedule({
|
|
178
180
|
toolCallId,
|
|
179
181
|
absolutePath,
|
|
180
|
-
thenRun
|
|
182
|
+
thenRun,
|
|
181
183
|
mutate,
|
|
182
184
|
signal,
|
|
183
185
|
ctx,
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Pi's Bash definition supplies the output schema and command-card renderers. */
|
|
2
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import type { JsonValue } from "@earendil-works/pi-ai";
|
|
4
|
+
import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { TObject } from "typebox";
|
|
6
|
+
import { Value } from "typebox/value";
|
|
7
|
+
|
|
8
|
+
export const nativeBash = createBashToolDefinition(process.cwd());
|
|
9
|
+
// ToolDefinition erases the type of outputSchema. Built-in Bash declares an object schema.
|
|
10
|
+
export const BASH_OUTPUT_SCHEMA = nativeBash.outputSchema as TObject;
|
|
11
|
+
const outputKeys = Object.keys(BASH_OUTPUT_SCHEMA.properties);
|
|
12
|
+
|
|
13
|
+
/** A partial or unreadable hook result can still establish a numeric exit. */
|
|
14
|
+
export function snapshotBashOutput(
|
|
15
|
+
result: Pick<AgentToolResult<unknown>, "structuredContent">,
|
|
16
|
+
recordObserverFailure: (error: unknown) => void,
|
|
17
|
+
) {
|
|
18
|
+
let exited = false;
|
|
19
|
+
try {
|
|
20
|
+
const value = result.structuredContent;
|
|
21
|
+
if (
|
|
22
|
+
value === null ||
|
|
23
|
+
typeof value !== "object" ||
|
|
24
|
+
!("exit_code" in value) ||
|
|
25
|
+
Array.isArray(value)
|
|
26
|
+
)
|
|
27
|
+
return { exited };
|
|
28
|
+
const exitCode = value.exit_code;
|
|
29
|
+
if (!Value.Check(BASH_OUTPUT_SCHEMA.properties.exit_code, exitCode)) return { exited };
|
|
30
|
+
exited = true;
|
|
31
|
+
const fields: Record<string, JsonValue> = {};
|
|
32
|
+
for (const key of outputKeys) {
|
|
33
|
+
const field = key === "exit_code" ? exitCode : value[key];
|
|
34
|
+
if (field !== undefined) fields[key] = field;
|
|
35
|
+
}
|
|
36
|
+
return { exited, structured: Value.Check(BASH_OUTPUT_SCHEMA, fields) ? fields : undefined };
|
|
37
|
+
} catch (error) {
|
|
38
|
+
recordObserverFailure(error);
|
|
39
|
+
return { exited };
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/pi/report-schema.ts
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
import { Type, type Static, type TObject, type TProperties, type TSchema } from "typebox";
|
|
19
19
|
import { literalUnion } from "./schema.ts";
|
|
20
|
+
import { BASH_OUTPUT_SCHEMA } from "./native-bash.ts";
|
|
20
21
|
|
|
21
22
|
const count = (description: string) => Type.Integer({ minimum: 1, description });
|
|
22
23
|
const opt = Type.Optional;
|
|
@@ -53,10 +54,10 @@ const FRESHNESS_SCHEMA = Type.Union([
|
|
|
53
54
|
]);
|
|
54
55
|
export type Freshness = Static<typeof FRESHNESS_SCHEMA>;
|
|
55
56
|
|
|
57
|
+
const EXIT_STATUS_SCHEMA = Type.Union([Type.Literal("succeeded"), Type.Literal("failed")]);
|
|
56
58
|
/** A then_run command's final status; `skipped` never started, `cancelled` may have. */
|
|
57
59
|
const COMMAND_STATUS_SCHEMA = Type.Union([
|
|
58
|
-
|
|
59
|
-
Type.Literal("failed"),
|
|
60
|
+
...EXIT_STATUS_SCHEMA.anyOf,
|
|
60
61
|
Type.Literal("timeout"),
|
|
61
62
|
Type.Literal("cancelled"),
|
|
62
63
|
Type.Literal("skipped"),
|
|
@@ -332,13 +333,9 @@ const FACT_FIELDS = {
|
|
|
332
333
|
"Use the freshness recovery instruction when the post-commit observation failed.",
|
|
333
334
|
),
|
|
334
335
|
|
|
335
|
-
//
|
|
336
|
-
// read `output` here.
|
|
336
|
+
// The model and TUI report only the follow-up status. Bash owns the command payloads.
|
|
337
337
|
then_run: modelFact(
|
|
338
|
-
Type.Object(
|
|
339
|
-
{ status: COMMAND_STATUS_SCHEMA, output: opt(Type.String()) },
|
|
340
|
-
{ additionalProperties: false },
|
|
341
|
-
),
|
|
338
|
+
Type.Object({ status: COMMAND_STATUS_SCHEMA }, { additionalProperties: false }),
|
|
342
339
|
"Act on the failure the output shows, and run the command separately when it did not run.",
|
|
343
340
|
),
|
|
344
341
|
progressError: tuiFact(CAUSE_SCHEMA),
|
|
@@ -586,7 +583,21 @@ type ReportFields = Static<typeof REPORT_SCHEMA>;
|
|
|
586
583
|
|
|
587
584
|
const TEXT_OUTPUT = { text: Type.String() };
|
|
588
585
|
const FILE_PUBLICATION = { publication: PUBLICATION_SCHEMA };
|
|
589
|
-
const MUTATION_OUTPUT =
|
|
586
|
+
const MUTATION_OUTPUT = {
|
|
587
|
+
...facts([], ["freshness", "freshnessError"]).properties,
|
|
588
|
+
then_run: opt(
|
|
589
|
+
Type.Union([
|
|
590
|
+
FACT_FIELDS.then_run.schema,
|
|
591
|
+
Type.Object(
|
|
592
|
+
{
|
|
593
|
+
status: EXIT_STATUS_SCHEMA,
|
|
594
|
+
...BASH_OUTPUT_SCHEMA.properties,
|
|
595
|
+
},
|
|
596
|
+
{ additionalProperties: false },
|
|
597
|
+
),
|
|
598
|
+
]),
|
|
599
|
+
),
|
|
600
|
+
};
|
|
590
601
|
|
|
591
602
|
function scriptOutput<P extends TProperties>(properties: P) {
|
|
592
603
|
const fields = { ...properties, next: REPORT_SCHEMA.properties.next };
|
|
@@ -672,7 +683,7 @@ const SUCCESS_SCHEMAS = REPORT_TOOLS.map((tool) =>
|
|
|
672
683
|
Type.Object(
|
|
673
684
|
{
|
|
674
685
|
...COMMON_WIRE_FIELDS,
|
|
675
|
-
...Type.
|
|
686
|
+
...Type.Pick(REPORT_SCHEMA, Object.keys(SCRIPT_OUTPUT_SCHEMAS[tool].properties)).properties,
|
|
676
687
|
...(isMutationTool(tool) ? MUTATION_PRESENTATION : {}),
|
|
677
688
|
tool: Type.Literal(tool),
|
|
678
689
|
},
|
|
@@ -737,7 +748,8 @@ export type SuccessOutcome = {
|
|
|
737
748
|
/** A success report may leave out facts the payload or originating call already shows. */
|
|
738
749
|
export type SuccessReport = {
|
|
739
750
|
[T in ReportTool]: ReportVariant<
|
|
740
|
-
SuccessEnvelope<T> &
|
|
751
|
+
SuccessEnvelope<T> &
|
|
752
|
+
Pick<ReportFields, Extract<keyof SuccessFacts<T>, keyof ReportFields> | "next">
|
|
741
753
|
>;
|
|
742
754
|
}[ReportTool];
|
|
743
755
|
|
package/src/pi/report.ts
CHANGED
|
@@ -169,12 +169,12 @@ function boundFacts<R extends Partial<Report>>(report: R, budget: OutputBudgets)
|
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
/**
|
|
172
|
-
* Project one complete outcome into the script fields
|
|
173
|
-
*
|
|
172
|
+
* Project one complete outcome into the script fields and report. The report follows the
|
|
173
|
+
* supplied payload and omits facts already shown by the call or payload.
|
|
174
174
|
*/
|
|
175
175
|
export function reportResult<TDetails extends object | undefined>(
|
|
176
176
|
outcome: SuccessOutcome,
|
|
177
|
-
|
|
177
|
+
payload: Content,
|
|
178
178
|
budget: OutputBudgets,
|
|
179
179
|
{
|
|
180
180
|
details,
|
|
@@ -186,7 +186,6 @@ export function reportResult<TDetails extends object | undefined>(
|
|
|
186
186
|
): AgentToolResult<TDetails & ReportDetails<SuccessReport>> {
|
|
187
187
|
const bounded = boundFacts(outcome, budget);
|
|
188
188
|
const command = bounded.then_run;
|
|
189
|
-
const payload: Content = command?.output ? [{ type: "text", text: command.output }] : toolPayload;
|
|
190
189
|
const complete = Object.fromEntries(reportEntries(bounded)) as SuccessReport;
|
|
191
190
|
if (bounded.callShowsNextOffset) delete complete.nextOffset;
|
|
192
191
|
if (bounded.payloadShowsCounts) {
|