@andares/pi-toolkits 0.12.2 → 0.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -18
- package/README.zh-CN.md +11 -11
- package/package.json +4 -4
- package/src/features/ask/reasons.ts +1 -1
- package/src/features/autostart/autostart.ts +1 -1
- package/src/features/autostart/index.ts +6 -3
- package/src/features/compact/index.ts +2 -2
- package/src/features/compact/prompt.ts +10 -8
- package/src/features/favorites/constants.ts +6 -3
- package/src/features/favorites/favorites.test.ts +25 -1
- package/src/features/favorites/patch-cycle.ts +8 -4
- package/src/features/favorites/patch-selector.ts +51 -18
- package/src/features/quit-guard/constants.ts +30 -5
- package/src/features/quit-guard/guard.ts +27 -6
- package/src/features/quit-guard/index.ts +31 -2
- package/src/features/quit-guard/quit-guard.test.ts +121 -4
- package/src/features/quit-guard/report.ts +1 -1
- package/src/features/quit-guard/store.ts +1 -1
- package/src/features/stash/stash.ts +1 -1
- package/src/lib/model-config.ts +1 -1
- package/src/lib/model-picker.ts +9 -6
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
In a nutshell: nine ready-to-use capabilities — **read-only consult mode** `ask`, **session-scoped boundary permission** `ask-perm`, **model favorites** `favorites`, **prompt stash** `stash`, **third-party code review** `third-review`, **dedicated compaction model** `compact-model`, **session startup automation** `autostart`, an **agent memory framework** `ask-init`, and a **quit watchdog** `quit-guard` — with more to come.
|
|
17
17
|
|
|
18
|
-
**Requirements**: pi `>=0.99.0`. Every published pi release from 0.99.0 through 1.5.
|
|
18
|
+
**Requirements**: pi `>=0.99.0`. Every published pi release from 0.99.0 through 1.5.1 has been verified with the full gate (install → `tsc --noEmit` → full test suite → keybinding audit → hash compare of the host files this package patches), each in a sandbox with the whole `@earendil-works/*` family pinned to the version under test. Newer releases are verified as they ship and the floor moves only when the measurement says so; `pnpm check:compat` reproduces the result. Note: pi ≥ 0.99 hosts require host-provided packages to be declared in `peerDependencies` with a `"*"` range — `@earendil-works/pi-tui` and `typebox` (the `scratchpad` tool builds a TypeBox schema) are declared that way; an installed copy in `dependencies` would make pi warn.
|
|
19
19
|
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -78,7 +78,7 @@ After installing, verify in any pi session:
|
|
|
78
78
|
| 🗜️ **compact** dedicated compaction model | `/compact-model` | give `/compact` and auto-compact a cheap fast model to summarize with, leaving the main model free to focus on the conversation; zero overhead when unconfigured, falls back to pi's default on any failure |
|
|
79
79
|
| 🚀 **autostart** session startup automation | `.pi/autostart.toml` | declare slash commands to run automatically at session start, per project (first use case: mounting multi-repo directories with `/add-dir`); never runs in untrusted directories, unregistered commands are skipped instead of being sent to the model |
|
|
80
80
|
| 🧠 **init** agent memory framework | `/ask-init` | install or adopt a fixed memory layout (`AGENTS.md` + `specs/` + `.agents/memory` + `.agents/implementations`), migrate an existing one with a snapshot and a coverage table, and audit it later for drift, budgets and duplicated facts |
|
|
81
|
-
| 🧯 **quit-guard** quit watchdog | `/quit-guard` | force-exit when
|
|
81
|
+
| 🧯 **quit-guard** quit watchdog | `/quit-guard` | force-exit when an interactive shutdown hangs, whether after the TUI teardown or before it on a signal-triggered quit; write a hang report and give the shell prompt back; TUI restarts and Ctrl+Z resume disarm it |
|
|
82
82
|
|
|
83
83
|
---
|
|
84
84
|
|
|
@@ -289,7 +289,7 @@ pi's `/compact` and auto-compact summarize the context **with the current sessio
|
|
|
289
289
|
| auto-compact threshold reached | summarized by the compaction model |
|
|
290
290
|
| context overflow recovery | summarized by the compaction model, retry behavior unchanged |
|
|
291
291
|
|
|
292
|
-
**Parts that are identical to pi's built-in behavior after takeover** (the built-in implementation is mirrored verbatim — copied from 0.87.1, byte-identical across 1.2.0 → 1.5.
|
|
292
|
+
**Parts that are identical to pi's built-in behavior after takeover** (the built-in implementation is mirrored verbatim — copied from 0.87.1, byte-identical across 1.2.0 → 1.5.1 apart from the two 1.4.0 fixes adopted here: summaries request the model's output limit instead of a fixed fraction of `reserveTokens`, and `/compact <instructions>` also reaches the split-turn prefix, plus the 1.5.0 `cost.totalFromProvider` merge rule in the usage accounting — and only the executing model changes; the conversation serializer itself is imported from the host, so it follows whatever the running host does, e.g. 1.2.0 stops feeding assistant thinking back into the summarization request):
|
|
293
293
|
|
|
294
294
|
- **Summary format** — the structured Goal / Progress / Key Decisions checkpoint; when a summary already exists, the iterative-update prompt is used so information carries over instead of being lost
|
|
295
295
|
- **Split behavior** — the `keepRecentTokens` retention policy, and `firstKeptEntryId` / `tokensBefore` passed back unchanged
|
|
@@ -370,7 +370,7 @@ An **identical command line** declared by both sources runs once: a duplicate is
|
|
|
370
370
|
|
|
371
371
|
**Key constraint: extension commands only**. Commands registered via `registerCommand` such as `/add-dir` (pi-add-dir) and `/cd` (pi-cd) work; built-in commands (`/compact`, `/reload`, `/resume`, …) are dispatched in the TUI layer and cannot be triggered from the extension layer; skill commands (`/skill:name`) are an expansion mechanism rather than an execution mechanism. The target extension you depend on (e.g. pi-add-dir) must be installed first.
|
|
372
372
|
|
|
373
|
-
> **Implementation notes**: execution uses `sendUserMessage(cmd, { expandPromptTemplates: true })` — that option routes `/cmd args` into command dispatch instead of the model prompt path (the wrapper defaults to `false`; `
|
|
373
|
+
> **Implementation notes**: execution uses `sendUserMessage(cmd, { expandPromptTemplates: true })` — that option routes `/cmd args` into command dispatch instead of the model prompt path (the wrapper defaults to `false`; `_tryExecuteExtensionCommand` is byte-identical across 1.2.0–1.5.1, and although 1.5.1 moved the rest of `sendUserMessage` into `_preparePrompt`, the extension-command branch is still its first early exit — see the host-compatibility discipline in AGENTS.md). Pre-validation uses `pi.getCommands()` (accepting only `source: "extension"`). Depends on `smol-toml` (zero-dependency, ~10KB, TOML 1.0).
|
|
374
374
|
|
|
375
375
|
---
|
|
376
376
|
|
|
@@ -461,8 +461,9 @@ package never directs the model which language to write or reply in.
|
|
|
461
461
|
**The problem.** pi's interactive `/quit` stops the TUI and then awaits every extension's
|
|
462
462
|
`session_shutdown` handler, one after another, **with no timeout**
|
|
463
463
|
(`runtimeHost.dispose()` → `emitSessionShutdownEvent()`; upstream
|
|
464
|
-
[issue #9997](https://github.com/earendil-works/pi/issues/9997), still unbounded in 1.5.
|
|
465
|
-
`main`
|
|
464
|
+
[issue #9997](https://github.com/earendil-works/pi/issues/9997), still unbounded in 1.5.1 and on
|
|
465
|
+
`main` — 1.5.1 added `await session.abort()` before the handler loop and a credential-write
|
|
466
|
+
settle after it, i.e. more awaits in the same untimed chain). One handler that never settles leaves pi alive at 0% CPU *after* the terminal has
|
|
466
467
|
already been restored and the final frame reprinted: the screen looks like a frozen "exit
|
|
467
468
|
screen", and the shell prompt never comes back. Ctrl+C and SIGTERM did not end the hung process
|
|
468
469
|
in our measurements (SIGKILL did); once that phase starts, the host has no way out of it.
|
|
@@ -472,10 +473,15 @@ Measured with a 20-extension setup (2026-11-05): a healthy quit spends 0.1–3 s
|
|
|
472
473
|
**What this does.** The guard watches the terminal instead of the event stream, so it still
|
|
473
474
|
works when the handler that hangs was loaded *before* this package (in that case our own
|
|
474
475
|
`session_shutdown` would never run). It arms on the TUI's teardown sequence
|
|
475
|
-
(`\x1b[?2004l` / `\x1b[?1049l`)
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
476
|
+
(`\x1b[?2004l` / `\x1b[?1049l`) — and, for the signal-triggered path (`kill -TERM`, a closed
|
|
477
|
+
window), on `session_shutdown` with reason `quit`, because that path runs every extension
|
|
478
|
+
handler *before* the TUI writes its teardown sequence: a stuck handler there would never produce
|
|
479
|
+
a marker. If the process is still alive `timeoutMs` later, it writes a hang report, restores the
|
|
480
|
+
terminal if the TUI never did (alternate screen, bracketed paste, cursor) and forces the exit.
|
|
481
|
+
A TUI that comes back disarms it — an interactive mode switch (`/settings` → TUI mode) and
|
|
482
|
+
Ctrl+Z suspend/resume both re-enter the TUI, and a live session must never be killed. The event
|
|
483
|
+
trigger is deliberately limited to TUI mode: RPC/JSON/print stdout is machine-readable and is
|
|
484
|
+
never given terminal escape sequences.
|
|
479
485
|
|
|
480
486
|
### Commands
|
|
481
487
|
|
|
@@ -485,21 +491,22 @@ must never be killed.
|
|
|
485
491
|
| `/quit-guard on` / `/quit-guard off` | enable/disable, persisted |
|
|
486
492
|
| `/quit-guard <ms>` | set the deadline (clamped to 2000–60000 ms), persisted |
|
|
487
493
|
|
|
488
|
-
**Configuration** —
|
|
489
|
-
|
|
494
|
+
**Configuration** — the guard is **on by default** (8 s after the teardown write, hang report
|
|
495
|
+
on), so an install is protected without any setup. It persists to
|
|
496
|
+
`<agent-dir>/pi-toolkits-quit-guard.json`, written by the commands; every field is optional:
|
|
490
497
|
|
|
491
498
|
```json
|
|
492
499
|
{
|
|
493
500
|
"enabled": true,
|
|
494
|
-
"timeoutMs":
|
|
501
|
+
"timeoutMs": 8000,
|
|
495
502
|
"report": true
|
|
496
503
|
}
|
|
497
504
|
```
|
|
498
505
|
|
|
499
506
|
`timeoutMs` counts **from the teardown write**, not from the moment you press Enter, so the time
|
|
500
|
-
the TUI spends stopping is not charged against a slow-but-finishing shutdown. Keep it
|
|
501
|
-
slowest healthy quit
|
|
502
|
-
end to end
|
|
507
|
+
the TUI spends stopping is not charged against a slow-but-finishing shutdown. Keep it above your
|
|
508
|
+
slowest healthy quit: the default is **8 s**, and the slowest healthy quit measured above was 5 s
|
|
509
|
+
end to end (of which ~2 s came after the teardown), leaving ~3 s of margin.
|
|
503
510
|
|
|
504
511
|
**Hang reports** — `<agent-dir>/quit-guard/quit-hang-<timestamp>-<pid>.json` records the
|
|
505
512
|
arm/fire timing, the teardown marker, and the process state at the deadline (`activeHandles`,
|
|
@@ -567,8 +574,8 @@ src/
|
|
|
567
574
|
├── permission/ # session-scoped boundary permission: modes, panel,
|
|
568
575
|
│ # bash units, policy, session grants, prompt,
|
|
569
576
|
│ # audit payload, tests
|
|
570
|
-
├── quit-guard/ # quit watchdog:
|
|
571
|
-
│ # store, hang report, tests
|
|
577
|
+
├── quit-guard/ # quit watchdog: TUI teardown + quit-event triggers,
|
|
578
|
+
│ # settings store, hang report, tests
|
|
572
579
|
├── review/ # third-party review: input/command triggers,
|
|
573
580
|
│ # review-model config store, prompt, tests
|
|
574
581
|
└── stash/ # prompt stash: hotkey state machine + tests
|
package/README.zh-CN.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
一句话介绍:目前包含九个开箱即用的功能——**只读咨询模式** `ask`、**会话级边界权限** `ask-perm`、**模型收藏** `favorites`、**提示词暂存** `stash`、**第三方代码评审** `third-review`、**独立压缩模型** `compact-model`、**会话启动自动化** `autostart`、**agent 记忆框架** `ask-init`、**退出看门狗** `quit-guard`,后续持续追加。
|
|
17
17
|
|
|
18
|
-
**版本要求**:pi `>=0.99.0`。0.99.0 到 1.5.
|
|
18
|
+
**版本要求**:pi `>=0.99.0`。0.99.0 到 1.5.1 的每一个已发布版本都用完整门禁实测过(install → `tsc --noEmit` → 全量测试 → 键位审计 → 对 patch 目标宿主文件做哈希比对),每个版本都在沙箱中把整个 `@earendil-works/*` 家族钉在同一版本。更新的版本随发布逐个验证,下限只在实测结果允许时移动;`pnpm check:compat` 可复现该结论。注:pi ≥ 0.99 的宿主要求「宿主提供的包」一律声明为 peerDependencies `"*"` —— `@earendil-works/pi-tui` 与 `typebox`(ask 的 `scratchpad` 用它构造参数 schema)都按此声明;若放进 `dependencies`,pi 会告警。
|
|
19
19
|
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -78,7 +78,7 @@ pi -e ./src/index.ts
|
|
|
78
78
|
| 🗜️ **compact** 独立压缩模型 | `/compact-model` | 给 `/compact` 与 auto-compact 配一个便宜快模型做总结,主模型专注对话;未配置零开销、任何异常回落 pi 默认 |
|
|
79
79
|
| 🚀 **autostart** 会话启动自动化 | `.pi/autostart.toml` | 项目内声明启动时自动执行的斜杠命令(首批用例:`/add-dir` 多仓库挂载);未信任不执行、未注册命令跳过不发给模型 |
|
|
80
80
|
| 🧠 **init** agent 记忆框架 | `/ask-init` | 安装或接管一套固定的记忆结构(`AGENTS.md` + `specs/` + `.agents/memory` + `.agents/implementations`),带快照与覆盖表迁移旧文档,之后可随时审计漂移、预算与重复事实 |
|
|
81
|
-
| 🧯 **quit-guard** 退出看门狗 | `/quit-guard` | TUI
|
|
81
|
+
| 🧯 **quit-guard** 退出看门狗 | `/quit-guard` | 交互式退出卡死时,无论发生在 TUI 收尾之后、还是信号触发路径的收尾之前,超时后写诊断报告并强制退出,把命令行提示符还给你;TUI 重启与 Ctrl+Z 恢复都会解除看守 |
|
|
82
82
|
|
|
83
83
|
---
|
|
84
84
|
|
|
@@ -289,7 +289,7 @@ pi 的 `/compact` 与 auto-compact 默认**用当前会话模型**做上下文
|
|
|
289
289
|
| auto-compact 阈值触发 | 压缩模型总结 |
|
|
290
290
|
| context overflow 恢复 | 压缩模型总结,重试行为不变 |
|
|
291
291
|
|
|
292
|
-
**接管后与 pi 内建行为完全一致的部分**(逐字同步 pi 内建实现,复制自 0.87.1、在 1.2.0 → 1.5.
|
|
292
|
+
**接管后与 pi 内建行为完全一致的部分**(逐字同步 pi 内建实现,复制自 0.87.1、在 1.2.0 → 1.5.1 内字节级不变 —— 除了此处采纳的两项 1.4.0 修正:摘要请求使用模型自身的输出上限而非 `reserveTokens` 的固定比例,以及 `/compact <instructions>` 也会进入 split-turn 前缀,外加 1.5.0 的 `cost.totalFromProvider` 合并规则(用量统计);只换执行模型;对话序列化函数(`serializeConversation`)是直接从宿主导入的,因此跟随宿主行为 —— 例如 1.2.0 起不再把 assistant thinking 回填进摘要请求):
|
|
293
293
|
|
|
294
294
|
- **摘要格式** —— Goal / Progress / Key Decisions 结构化 checkpoint;已有摘要时用迭代更新版 prompt,信息延续不丢
|
|
295
295
|
- **切分行为** —— 保留最近 `keepRecentTokens` 的策略、`firstKeptEntryId` / `tokensBefore` 原样回传,不动
|
|
@@ -370,7 +370,7 @@ run = [
|
|
|
370
370
|
|
|
371
371
|
**关键约束:只支持扩展命令**。`/add-dir`(pi-add-dir)、`/cd`(pi-cd)等 `registerCommand` 注册的命令可以;内置命令(`/compact`、`/reload`、`/resume`…)在 TUI 层分发,扩展层触发不了;skill 命令(`/skill:name`)是展开机制而非执行机制。依赖的目标扩展(如 pi-add-dir)需要先安装。
|
|
372
372
|
|
|
373
|
-
> **实现说明**:执行用 `sendUserMessage(cmd, { expandPromptTemplates: true })` —— 该选项把 `/cmd args` 路由到命令分发而不是模型 prompt 路径(包装层默认 `false
|
|
373
|
+
> **实现说明**:执行用 `sendUserMessage(cmd, { expandPromptTemplates: true })` —— 该选项把 `/cmd args` 路由到命令分发而不是模型 prompt 路径(包装层默认 `false`;`_tryExecuteExtensionCommand` 在 1.2.0–1.5.1 全区间字节级一致,1.5.1 虽把 `sendUserMessage` 其余部分重构进 `_preparePrompt`,扩展命令分支仍是它最前面的早退路径,见 AGENTS.md 宿主兼容纪律)。预校验用 `pi.getCommands()`(只认 `source: "extension"`)。依赖 `smol-toml`(零依赖、~10KB、TOML 1.0)。
|
|
374
374
|
|
|
375
375
|
---
|
|
376
376
|
|
|
@@ -443,9 +443,9 @@ run = [
|
|
|
443
443
|
<a name="quit-guard"></a>
|
|
444
444
|
|
|
445
445
|
**要解决的问题**。pi 的 `/quit` 先停 TUI,然后**逐个 await** 每个扩展的 `session_shutdown` 处理器,且**没有任何超时**(`runtimeHost.dispose()` → `emitSessionShutdownEvent()`;上游
|
|
446
|
-
[issue #9997](https://github.com/earendil-works/pi/issues/9997),1.5.
|
|
446
|
+
[issue #9997](https://github.com/earendil-works/pi/issues/9997),1.5.1 与 `main` 至今未修,1.5.1 还在处理器循环前加了 `await session.abort()`、之后加了凭据写盘等待——同一条没有超时的链上又多了两个 await)。只要有一个处理器永不 settle,pi 就会在终端已还原、最后一帧已重绘之后,以 0% CPU 永远挂着:画面看起来像「停在退出界面」,提示符再也不回来;实测 Ctrl+C 与 SIGTERM 都无法结束这个进程(只有 SIGKILL 有效)——进了这段收尾,宿主自己也没有出口。20 个扩展的环境实测(2026-11-05):健康退出在这段收尾上花 0.1–3 秒,`pi -ne` 0.12 秒;同一环境三次 `/quit` 就有一次**永远不结束**。
|
|
447
447
|
|
|
448
|
-
**这个功能做什么**。看守盯的是**终端写出的收尾序列**,而不是事件流——所以即使卡死的处理器比本包**先**加载(那样我们自己的 `session_shutdown` 根本不会运行),它照样能触发。它在 TUI 收尾序列(`\x1b[?2004l` / `\x1b[?1049l`)
|
|
448
|
+
**这个功能做什么**。看守盯的是**终端写出的收尾序列**,而不是事件流——所以即使卡死的处理器比本包**先**加载(那样我们自己的 `session_shutdown` 根本不会运行),它照样能触发。它在 TUI 收尾序列(`\x1b[?2004l` / `\x1b[?1049l`)出现时开始计时;**信号触发的退出**(`kill -TERM`、关窗 SIGHUP)另有一只触发源:`session_shutdown` 且 reason 为 `quit`——那条路是**先跑完所有扩展处理器再停 TUI**,处理器挂住时收尾序列永远写不出来,只靠序列就会漏掉。若 `timeoutMs` 之后进程还活着,它写一份诊断报告;若 TUI 从没恢复过终端,它先做恢复(退备用屏、关括号粘贴、显示光标)再强制退出。TUI **回来**时自动解除:`/settings` 里切换 TUI 显示模式、Ctrl+Z 挂起后 `fg` 恢复,都会让 TUI 重新进入,绝不能误杀活着的会话。事件触发源只限 TUI 模式:RPC/JSON/print 的 stdout 是机器可读协议,绝不会被写入终端转义序列。
|
|
449
449
|
|
|
450
450
|
### 命令
|
|
451
451
|
|
|
@@ -455,17 +455,17 @@ run = [
|
|
|
455
455
|
| `/quit-guard on` / `/quit-guard off` | 开启/关闭,并持久化 |
|
|
456
456
|
| `/quit-guard <ms>` | 设置超时(钳制在 2000–60000 ms),并持久化 |
|
|
457
457
|
|
|
458
|
-
**配置** —— `<agent-dir>/pi-toolkits-quit-guard.json`,由命令写入;所有字段都可省略:
|
|
458
|
+
**配置** —— 看守**默认开启**(收尾序列写出后 8 秒、写诊断报告),装上就有保护,不用先配置。状态持久化在 `<agent-dir>/pi-toolkits-quit-guard.json`,由命令写入;所有字段都可省略:
|
|
459
459
|
|
|
460
460
|
```json
|
|
461
461
|
{
|
|
462
462
|
"enabled": true,
|
|
463
|
-
"timeoutMs":
|
|
463
|
+
"timeoutMs": 8000,
|
|
464
464
|
"report": true
|
|
465
465
|
}
|
|
466
466
|
```
|
|
467
467
|
|
|
468
|
-
`timeoutMs` 从**收尾序列写出**那一刻开始算,不是从你按下 Enter 开始算——TUI 自己停下来的时间不计入,所以「慢但能完成」的收尾(记忆库 flush、MCP 关闭)
|
|
468
|
+
`timeoutMs` 从**收尾序列写出**那一刻开始算,不是从你按下 Enter 开始算——TUI 自己停下来的时间不计入,所以「慢但能完成」的收尾(记忆库 flush、MCP 关闭)不会被误杀。默认 **8 秒**;上例实测最慢的健康退出端到端 5 秒(其中约 2 秒发生在收尾之后),余量约 3 秒。
|
|
469
469
|
|
|
470
470
|
**诊断报告** —— `<agent-dir>/quit-guard/quit-hang-<时间戳>-<pid>.json`,记录开始计时/触发的时间、触发用的收尾序列,以及截止时进程的状态(`activeHandles`、`activeRequests`、宿主 libuv 句柄表)。**进程还活着但 `libuv` 表是空的**,就是「有个 Promise 永远不会 settle」的特征,区别于阻塞的 socket 或残留子进程。报告文件**仅本人可读**(0700 目录下的 0600 文件),进程参数按审批日志同一套规则脱敏,所以 `pi --api-key …` 不会把密钥留在盘上。
|
|
471
471
|
|
|
@@ -519,8 +519,8 @@ src/
|
|
|
519
519
|
├── permission/ # 会话级边界权限:模式、面板、bash 拆解、
|
|
520
520
|
│ # 策略、会话授权、确认对话框、
|
|
521
521
|
│ # 审计 payload、测试
|
|
522
|
-
├── quit-guard/ #
|
|
523
|
-
│ #
|
|
522
|
+
├── quit-guard/ # 退出看门狗:TUI 收尾 + quit 事件双触发、
|
|
523
|
+
│ # 配置存储、诊断报告、测试
|
|
524
524
|
├── review/ # 第三方评审:输入/指令触发、
|
|
525
525
|
│ # 评审模型配置存储、提示词、测试
|
|
526
526
|
└── stash/ # 提示词暂存:热键状态机 + 测试
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andares/pi-toolkits",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.3",
|
|
4
4
|
"description": "Integrated toolkit extension for pi — ask mode (read-only Q&A), session-scoped permission checks, model favorites, prompt stash, third-party code review, session autostart, a dedicated compaction model, and an agent memory framework (/ask-init)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -47,9 +47,9 @@
|
|
|
47
47
|
"smol-toml": "^1.9.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@earendil-works/pi-ai": "^1.5.
|
|
51
|
-
"@earendil-works/pi-coding-agent": "^1.5.
|
|
52
|
-
"@earendil-works/pi-tui": "^1.5.
|
|
50
|
+
"@earendil-works/pi-ai": "^1.5.1",
|
|
51
|
+
"@earendil-works/pi-coding-agent": "^1.5.1",
|
|
52
|
+
"@earendil-works/pi-tui": "^1.5.1",
|
|
53
53
|
"@types/node": "^26.6.2",
|
|
54
54
|
"typebox": "^1.3.27",
|
|
55
55
|
"typescript": "^5.6.0",
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* ask feature — actionable rejection messages.
|
|
3
3
|
*
|
|
4
4
|
* The `tool_call` hook's `reason` is delivered to the model as the tool result
|
|
5
|
-
* (verified against pi 1.5.
|
|
5
|
+
* (verified against pi 1.5.1: `extensions/runner.js` returns the `{block,
|
|
6
6
|
* reason}` result unchanged and pi-agent-core's `agent-loop.js` turns it into
|
|
7
7
|
* `createErrorToolResult(reason)`; both paths are byte-identical to 1.2.0), so
|
|
8
8
|
* it is the best place to name the nearest allowed alternative and stop the model
|
|
@@ -48,7 +48,7 @@ export const RUNNABLE_REASONS: ReadonlySet<string> = new Set([
|
|
|
48
48
|
* `-r` (`--resume`), `--session <path>` and `--fork <path>` all open an
|
|
49
49
|
* existing session *before* the first runtime exists, and that runtime is
|
|
50
50
|
* created without an explicit session_start event, so extensions see pi's
|
|
51
|
-
* default reason — `startup` — not `resume` (verified on pi 1.2.0–1.5.
|
|
51
|
+
* default reason — `startup` — not `resume` (verified on pi 1.2.0–1.5.1:
|
|
52
52
|
* `main.js` builds the initial session manager from those flags and calls
|
|
53
53
|
* `createAgentSessionRuntime` with no `sessionStartEvent`;
|
|
54
54
|
* `agent-session.js` defaults it to `{ reason: "startup" }`). `resume` is only
|
|
@@ -26,9 +26,12 @@
|
|
|
26
26
|
* Dispatch uses `sendUserMessage(cmd, { expandPromptTemplates: true })` —
|
|
27
27
|
* that flag is what routes "/cmd args" through _tryExecuteExtensionCommand
|
|
28
28
|
* instead of the model prompt path. The wrapper defaults it to false in this
|
|
29
|
-
* package
|
|
30
|
-
* window
|
|
31
|
-
*
|
|
29
|
+
* package. `_tryExecuteExtensionCommand` is byte-identical across every
|
|
30
|
+
* published version of the supported window (1.2.0 → 1.5.1); `sendUserMessage`
|
|
31
|
+
* itself was refactored in 1.5.1 (the rest of the body moved into
|
|
32
|
+
* `_preparePrompt`, #9154), but the extension-command branch is still the
|
|
33
|
+
* first early exit of the wrapper, so `/cmd args` never reaches the model
|
|
34
|
+
* prompt path. See AGENTS.md host-compat discipline for the version matrix.
|
|
32
35
|
*
|
|
33
36
|
* Only extension commands can run this way. Built-in commands (/compact,
|
|
34
37
|
* /reload, /resume, …) are dispatched at the TUI layer and cannot be
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* the summary file-list tail are verbatim pi built-in behavior (copied
|
|
14
14
|
* from 0.87.1; `core/compaction/compaction.js` stayed byte-identical
|
|
15
15
|
* 1.0.0 → 1.3.0, 1.4.0 changed only the summary output budget and
|
|
16
|
-
* the split-turn focus handling mirrored below, and 1.5.0 left it
|
|
16
|
+
* the split-turn focus handling mirrored below, and 1.5.0 / 1.5.1 left it
|
|
17
17
|
* untouched; the only mirrored helper that moved after that span is
|
|
18
18
|
* `combineUsage`, see prompt.ts) — only the executing
|
|
19
19
|
* model differs. The one exception is `serializeConversation`, which is
|
|
@@ -135,7 +135,7 @@ async function completeSummary(
|
|
|
135
135
|
* over).
|
|
136
136
|
*
|
|
137
137
|
* 1.4.0 changed two things this mirror covers, and we follow 1.4.0 for every
|
|
138
|
-
* host in the supported window (1.2.0 → 1.5.
|
|
138
|
+
* host in the supported window (1.2.0 → 1.5.1) because both are bug fixes
|
|
139
139
|
* rather than behavior we could sensibly keep per version:
|
|
140
140
|
* - summaries no longer cap maxTokens at 0.8/0.5 × reserveTokens; the
|
|
141
141
|
* request omits maxTokens so the provider uses the model's output limit
|
|
@@ -6,14 +6,16 @@
|
|
|
6
6
|
* summaries produced by the configured compact model are formatted exactly
|
|
7
7
|
* like pi's own compaction output. Only the executing model differs.
|
|
8
8
|
* Verified byte-identical against every published version of the supported
|
|
9
|
-
* window (1.2.0 → 1.5.
|
|
10
|
-
* thinking from serializeConversation
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
9
|
+
* window (1.2.0 → 1.5.1): the only utils.js changes (1.2.0 dropping assistant
|
|
10
|
+
* thinking from serializeConversation; 1.5.1 routing `truncateText` through
|
|
11
|
+
* `sliceHead` so a truncation never splits a surrogate pair) do not touch the
|
|
12
|
+
* strings mirrored here — that serializer is imported from the host, not
|
|
13
|
+
* mirrored — compaction.js last changed in 1.4.0, in the output budget and
|
|
14
|
+
* the split-turn focus handling (both adopted here, see
|
|
15
|
+
* buildTurnPrefixPromptText) and is untouched in 1.5.1, and
|
|
16
|
+
* core/usage-totals.js changed once past that point, in 1.5.0, which only
|
|
17
|
+
* added the `cost.totalFromProvider` merge rule mirrored below (the numeric
|
|
18
|
+
* fields are untouched; 1.5.1 left it alone). 0.87.0 shipped a
|
|
17
19
|
* different split-turn prefix prompt; the text mirrored here is 0.87.1's
|
|
18
20
|
* fix, and the mirror is the only variant any supported host gets
|
|
19
21
|
* — intentional.
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* keybinding conflicts arise.
|
|
10
10
|
*
|
|
11
11
|
* Verified against every published version of the supported range
|
|
12
|
-
* (0.99.0 → 1.5.
|
|
12
|
+
* (0.99.0 → 1.5.1) keybinding tables + pi-tui input dispatch on WSL2 +
|
|
13
13
|
* Windows Terminal; re-run `pnpm check:keybindings` after every host upgrade
|
|
14
14
|
* before trusting this.
|
|
15
15
|
*/
|
|
@@ -31,7 +31,7 @@ export const FAVORITES_FILE = "pi-toolkits-favorites.json";
|
|
|
31
31
|
* `TuiAltScreen.handleViewportInput()` checks it before
|
|
32
32
|
* `shouldDeferViewportInput()` (named `shouldDeferViewportInputToOverlay()`
|
|
33
33
|
* through 1.4.0), so the keystroke opens transcript
|
|
34
|
-
* search and the selector never sees it (verified in pi-tui 1.5.
|
|
34
|
+
* search and the selector never sees it (verified in pi-tui 1.5.1
|
|
35
35
|
* `dist/tui-alt-screen.js`: the search check is still the first key branch
|
|
36
36
|
* and still returns `{ consume: true }` unconditionally; the 1.5.0 changes to
|
|
37
37
|
* that file are exit/teardown, word-selection joiners, and a rename of
|
|
@@ -39,7 +39,10 @@ export const FAVORITES_FILE = "pi-toolkits-favorites.json";
|
|
|
39
39
|
* which now also defers viewport keys to a focused component that declares
|
|
40
40
|
* `capturesViewportInput`, but that guard sits BELOW the search branch, so
|
|
41
41
|
* it does not rescue ctrl+f for the selector even though 1.5.0 gives the
|
|
42
|
-
* selector `capturesViewportInput = true
|
|
42
|
+
* selector `capturesViewportInput = true`; 1.5.1's only change to that file
|
|
43
|
+
* is Kitty image draw ordering, and its only keybinding-table change is
|
|
44
|
+
* adding `ctrl+v` next to `alt+v` for `app.clipboard.pasteImage` on
|
|
45
|
+
* Windows/WSL — neither touches this key).
|
|
43
46
|
*
|
|
44
47
|
* Why ctrl+alt+f was discarded: clean at the pi layer across 1.1–1.5 (only
|
|
45
48
|
* ctrl+alt+] is taken from that family) and byte-distinguishable without
|
|
@@ -42,6 +42,7 @@ import { applyCyclePatch } from "./patch-cycle.js";
|
|
|
42
42
|
import { styleFavorite } from "./constants.js";
|
|
43
43
|
import {
|
|
44
44
|
applyModelSelectorPatches,
|
|
45
|
+
runFilterModels,
|
|
45
46
|
setSelectorThemeProvider,
|
|
46
47
|
} from "./patch-selector.js";
|
|
47
48
|
|
|
@@ -357,7 +358,7 @@ interface FakeSelector {
|
|
|
357
358
|
__favoritesHint?: { setText(_t: string): void };
|
|
358
359
|
handleInput(d: string): void;
|
|
359
360
|
updateList(): void;
|
|
360
|
-
filterModels(q: string): void;
|
|
361
|
+
filterModels(q: string, preferredModel?: ModelLike): void;
|
|
361
362
|
}
|
|
362
363
|
|
|
363
364
|
function item(model: ModelLike) {
|
|
@@ -466,6 +467,29 @@ describe("selector patches", () => {
|
|
|
466
467
|
]);
|
|
467
468
|
});
|
|
468
469
|
|
|
470
|
+
it("forwards pi 1.5.1's preferredModel through the favorites-only swap", () => {
|
|
471
|
+
getFavoritesStore().toggle(models[0]);
|
|
472
|
+
const calls: Array<[string, ModelLike | undefined, number]> = [];
|
|
473
|
+
// Host-independent: the spy stands in for whatever the installed host
|
|
474
|
+
// declares. 1.2.0–1.5.0 ignore the extra argument; 1.5.1+ use it.
|
|
475
|
+
const original = function (
|
|
476
|
+
this: FakeSelector,
|
|
477
|
+
query: string,
|
|
478
|
+
preferredModel?: ModelLike,
|
|
479
|
+
) {
|
|
480
|
+
calls.push([query, preferredModel, this.activeModels.length]);
|
|
481
|
+
};
|
|
482
|
+
const selector = fakeSelector({
|
|
483
|
+
activeModels: models.map(item),
|
|
484
|
+
__favoritesOnly: true,
|
|
485
|
+
});
|
|
486
|
+
runFilterModels(selector, original, "claude", models[1]);
|
|
487
|
+
// One call, preferred model intact, and it ran on the one-entry subset…
|
|
488
|
+
expect(calls).toEqual([["claude", models[1], 1]]);
|
|
489
|
+
// …with the full list restored afterwards.
|
|
490
|
+
expect(selector.activeModels).toHaveLength(3);
|
|
491
|
+
});
|
|
492
|
+
|
|
469
493
|
it("mirrors pi 1.5.0's disambiguating model name after the id", () => {
|
|
470
494
|
// The name is shown only when it adds words the id does not convey
|
|
471
495
|
// (pi's getDistinctModelName rule, copied — it is not exported).
|
|
@@ -15,9 +15,13 @@
|
|
|
15
15
|
* model available" feedback); otherwise jump to it
|
|
16
16
|
* - the apply logic mirrors pi's _cycleScopedModel/_cycleAvailableModel
|
|
17
17
|
* (byte-identical across every published version in the supported window
|
|
18
|
-
* 1.2.0 → 1.5.
|
|
19
|
-
* tool-restore rewrites
|
|
20
|
-
*
|
|
18
|
+
* 1.2.0 → 1.5.1 — `cycleModel` itself is untouched by 1.4.0's recovery and
|
|
19
|
+
* tool-restore rewrites, by 1.5.0's auth-routing/loadout-ordering changes
|
|
20
|
+
* and by 1.5.1's extraction of the index math into `getNextCycleIndex`
|
|
21
|
+
* (that refactor lives in `_cycleScopedModel`/`_cycleAvailableModel`, which
|
|
22
|
+
* this patch replaces rather than calls; the semantics it encodes —
|
|
23
|
+
* wrap-around, and "current model not in the list → forward first /
|
|
24
|
+
* backward last" — are what nextCycleIndex below already does):
|
|
21
25
|
* state swap, session persistence, default-model persistence only when
|
|
22
26
|
* `options.persist` is set, thinking-level re-clamp, model_select emit
|
|
23
27
|
* with source "cycle")
|
|
@@ -35,7 +39,7 @@ import { getFavoritesStore, modelKey } from "./store.js";
|
|
|
35
39
|
* pi's `Model<any>` — the exact type of `ModelCycleResult.model`
|
|
36
40
|
* (pi-coding-agent 1.2–1.5; the field is unchanged across that span).
|
|
37
41
|
* Derived here instead of importing `Model` from @earendil-works/pi-ai,
|
|
38
|
-
* whose index.d.ts (1.2 through 1.5.
|
|
42
|
+
* whose index.d.ts (1.2 through 1.5.1 alike) re-exports it via an
|
|
39
43
|
* extensioned `"./types.ts"` specifier that not every TS resolver substitutes
|
|
40
44
|
* to `types.d.ts` (tsc 5.9 bundler does; other tsserver builds don't).
|
|
41
45
|
*/
|
|
@@ -22,9 +22,13 @@
|
|
|
22
22
|
* keeps loading and ctrl+p falls back to stock behavior. The prototype
|
|
23
23
|
* shape touched here (handleInput/updateList/filterModels and the instance
|
|
24
24
|
* fields below) is unchanged across the mandatory window
|
|
25
|
-
* pi 1.2.0 → 1.5.
|
|
25
|
+
* pi 1.2.0 → 1.5.1 (and exercised by the 0.99.0 → 1.1.0 backward probes).
|
|
26
26
|
* updateList gained one layout change in 1.5.0 — the disambiguating model
|
|
27
27
|
* name after the id — mirrored here; see distinctModelName below.
|
|
28
|
+
* filterModels gained a second `preferredModel` argument in 1.5.1 (keep the
|
|
29
|
+
* selection when a background catalog refresh lands, #9109). The override
|
|
30
|
+
* forwards it as-is: hosts before 1.5.1 ignore the extra argument, hosts from
|
|
31
|
+
* 1.5.1 keep the highlighted row instead of jumping back to the top.
|
|
28
32
|
*/
|
|
29
33
|
import {
|
|
30
34
|
ModelSelectorComponent,
|
|
@@ -62,7 +66,8 @@ interface ListContainerLike {
|
|
|
62
66
|
interface SelectorPatchTarget {
|
|
63
67
|
handleInput(keyData: string): void;
|
|
64
68
|
updateList(): void;
|
|
65
|
-
|
|
69
|
+
/** pi 1.5.1+: `preferredModel` is forwarded to the built-in implementation. */
|
|
70
|
+
filterModels(query: string, preferredModel?: ModelRef): void;
|
|
66
71
|
/** pi 1.0–1.5: default-model badge source. */
|
|
67
72
|
isDefaultModel(model: ModelRef): boolean;
|
|
68
73
|
listContainer: ListContainerLike;
|
|
@@ -86,6 +91,44 @@ interface SelectorPatchTarget {
|
|
|
86
91
|
|
|
87
92
|
let themeProvider: () => Theme | undefined = () => undefined;
|
|
88
93
|
|
|
94
|
+
/** The slice of the selector the "only favorites" swap reads and writes. */
|
|
95
|
+
export interface FilterModelsScope {
|
|
96
|
+
activeModels: Array<{ model: ModelRef }>;
|
|
97
|
+
__favoritesOnly?: boolean;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Core of the `filterModels` override, kept callable so the favorites-only
|
|
102
|
+
* swap and the `preferredModel` forwarding can be tested without depending
|
|
103
|
+
* on which host is installed.
|
|
104
|
+
*
|
|
105
|
+
* `preferredModel` is pi 1.5.1's second argument (#9109: keep the highlighted
|
|
106
|
+
* row when a background catalog refresh lands). It is forwarded unconditionally
|
|
107
|
+
* because every host before 1.5.1 declares one parameter and ignores the extra
|
|
108
|
+
* argument; dropping it here would silently restore the jump-to-top behavior
|
|
109
|
+
* on 1.5.1+.
|
|
110
|
+
*/
|
|
111
|
+
export function runFilterModels(
|
|
112
|
+
target: FilterModelsScope,
|
|
113
|
+
original: (query: string, preferredModel?: ModelRef) => void,
|
|
114
|
+
query: string,
|
|
115
|
+
preferredModel?: ModelRef,
|
|
116
|
+
): void {
|
|
117
|
+
if (!target.__favoritesOnly) {
|
|
118
|
+
original.call(target, query, preferredModel);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const saved = target.activeModels;
|
|
122
|
+
target.activeModels = saved.filter((item) =>
|
|
123
|
+
getFavoritesStore().has(item.model),
|
|
124
|
+
);
|
|
125
|
+
try {
|
|
126
|
+
original.call(target, query, preferredModel);
|
|
127
|
+
} finally {
|
|
128
|
+
target.activeModels = saved;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
89
132
|
/** Called by registerFavorites once the live theme proxy is available. */
|
|
90
133
|
export function setSelectorThemeProvider(
|
|
91
134
|
provider: () => Theme | undefined,
|
|
@@ -149,9 +192,10 @@ let patched = false;
|
|
|
149
192
|
export function applyModelSelectorPatches(): boolean {
|
|
150
193
|
if (patched) return true;
|
|
151
194
|
// SAFETY: ModelSelectorComponent's members are TS-private (compile-time
|
|
152
|
-
// only); the structural view matches pi 1.0–1.5's prototype shape
|
|
153
|
-
//
|
|
154
|
-
// existence-checked below before any
|
|
195
|
+
// only); the structural view matches pi 1.0–1.5.1's prototype shape (same
|
|
196
|
+
// methods across that span; 1.5.1 only added filterModels' optional second
|
|
197
|
+
// parameter) and every touched method is existence-checked below before any
|
|
198
|
+
// patching happens.
|
|
155
199
|
const proto =
|
|
156
200
|
ModelSelectorComponent.prototype as unknown as SelectorPatchTarget;
|
|
157
201
|
if (
|
|
@@ -282,20 +326,9 @@ export function applyModelSelectorPatches(): boolean {
|
|
|
282
326
|
proto.filterModels = function (
|
|
283
327
|
this: SelectorPatchTarget,
|
|
284
328
|
query: string,
|
|
329
|
+
preferredModel?: ModelRef,
|
|
285
330
|
): void {
|
|
286
|
-
|
|
287
|
-
const saved = this.activeModels;
|
|
288
|
-
this.activeModels = saved.filter((item) =>
|
|
289
|
-
getFavoritesStore().has(item.model),
|
|
290
|
-
);
|
|
291
|
-
try {
|
|
292
|
-
originalFilterModels.call(this, query);
|
|
293
|
-
} finally {
|
|
294
|
-
this.activeModels = saved;
|
|
295
|
-
}
|
|
296
|
-
} else {
|
|
297
|
-
originalFilterModels.call(this, query);
|
|
298
|
-
}
|
|
331
|
+
runFilterModels(this, originalFilterModels, query, preferredModel);
|
|
299
332
|
};
|
|
300
333
|
|
|
301
334
|
// ── helpers injected onto the prototype ───────────────────────────────
|
|
@@ -40,12 +40,14 @@ export const QUIT_GUARD_REPORT_DIR = "quit-guard";
|
|
|
40
40
|
*
|
|
41
41
|
* Measured on a 20-extension setup (2026-11-05): a healthy `/quit` spends
|
|
42
42
|
* ~0.1–3 s between the teardown write and `process.exit(0)` (the whole
|
|
43
|
-
* `runtimeHost.dispose()` / extension-shutdown phase),
|
|
44
|
-
* `pi -ne`.
|
|
45
|
-
* (
|
|
46
|
-
* prompt
|
|
43
|
+
* `runtimeHost.dispose()` / extension-shutdown phase), 5 s worst case end to
|
|
44
|
+
* end, and 0.12 s with `pi -ne`. 8 s keeps ~3 s of margin over the slowest
|
|
45
|
+
* healthy quit observed (enough for a memory flush or an MCP server close)
|
|
46
|
+
* while returning the prompt sooner than the original 10 s when something
|
|
47
|
+
* never settles. Set by the operator (2026-11-10); it is a default, not a
|
|
48
|
+
* floor — `/quit-guard <ms>` still overrides it.
|
|
47
49
|
*/
|
|
48
|
-
export const DEFAULT_TIMEOUT_MS =
|
|
50
|
+
export const DEFAULT_TIMEOUT_MS = 8_000;
|
|
49
51
|
|
|
50
52
|
/** Floor for `/quit-guard <ms>`: below this, a healthy slow quit would be cut. */
|
|
51
53
|
export const MIN_TIMEOUT_MS = 2_000;
|
|
@@ -56,5 +58,28 @@ export const MAX_TIMEOUT_MS = 60_000;
|
|
|
56
58
|
/** Sequences after which the interactive TUI has begun tearing down. */
|
|
57
59
|
export const TEARDOWN_MARKERS = ["\x1b[?2004l", "\x1b[?1049l"] as const;
|
|
58
60
|
|
|
61
|
+
/**
|
|
62
|
+
* Pseudo-marker for the second, event-driven trigger.
|
|
63
|
+
*
|
|
64
|
+
* `shutdown({ fromSignal: true })` runs every extension's `session_shutdown`
|
|
65
|
+
* handler BEFORE `ui.stop()` writes the teardown sequence (pi 1.5.1,
|
|
66
|
+
* interactive-mode.js). With a handler that never settles, the marker is never
|
|
67
|
+
* written and a sequence-only watchdog stays asleep: the process keeps the
|
|
68
|
+
* terminal, raw mode and the frozen frame forever. `session_shutdown` with
|
|
69
|
+
* reason `"quit"` is the only in-process signal available at that point, so it
|
|
70
|
+
* arms the guard too. Session replacements use `"new"`/`"resume"`/`"fork"`
|
|
71
|
+
* and `/reload` uses `"reload"` — those must never arm it.
|
|
72
|
+
*/
|
|
73
|
+
export const SHUTDOWN_EVENT_MARKER = "session_shutdown";
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Terminal restore written before a forced exit that never reached
|
|
77
|
+
* `ui.stop()`: leave the alternate screen, disable bracketed paste, show the
|
|
78
|
+
* cursor, reset attributes. Harmless when the TUI already restored (the
|
|
79
|
+
* marker-armed path never writes it) and the only thing that makes the shell
|
|
80
|
+
* usable when it did not.
|
|
81
|
+
*/
|
|
82
|
+
export const TERMINAL_RESTORE = "\x1b[?2004l\x1b[?1049l\x1b[?25h\x1b[0m\r\n";
|
|
83
|
+
|
|
59
84
|
/** Sequences that mean a TUI is starting (mode switch or suspend/resume). */
|
|
60
85
|
export const RESTART_MARKERS = ["\x1b[?2004h", "\x1b[?1049h"] as const;
|
|
@@ -19,7 +19,11 @@
|
|
|
19
19
|
* first, and the token check drops a fire whose arm was superseded;
|
|
20
20
|
* - disabled means inert: it never arms and disarms immediately.
|
|
21
21
|
*/
|
|
22
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
RESTART_MARKERS,
|
|
24
|
+
SHUTDOWN_EVENT_MARKER,
|
|
25
|
+
TEARDOWN_MARKERS,
|
|
26
|
+
} from "./constants.js";
|
|
23
27
|
|
|
24
28
|
/** A chunk as written to `process.stdout` (string, or Buffer/typed array). */
|
|
25
29
|
export type GuardChunk = string | Uint8Array;
|
|
@@ -104,7 +108,7 @@ export class QuitGuard {
|
|
|
104
108
|
constructor(timeoutMs: number, deps: QuitGuardDeps) {
|
|
105
109
|
this.timeoutMs = timeoutMs;
|
|
106
110
|
// performance.now() is monotonic: a wall-clock jump (NTP, WSL VM
|
|
107
|
-
// resume, manual `date`) must not make
|
|
111
|
+
// resume, manual `date`) must not make an 8 s deadline look like 5 s,
|
|
108
112
|
// and `elapsedMs` in the hang report must measure real time spent.
|
|
109
113
|
this.now = deps.now ?? (() => performance.now());
|
|
110
114
|
this.schedule =
|
|
@@ -138,6 +142,18 @@ export class QuitGuard {
|
|
|
138
142
|
this.disarm();
|
|
139
143
|
}
|
|
140
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Arm from a `session_shutdown` (reason `"quit"`) event, for shutdowns that
|
|
147
|
+
* hang before the TUI writes its teardown sequence — the signal-triggered
|
|
148
|
+
* path runs extension handlers first, so a stuck handler there never
|
|
149
|
+
* produces a marker. No-op when a teardown marker already armed the guard,
|
|
150
|
+
* so the measured deadline still starts at the earliest evidence.
|
|
151
|
+
*/
|
|
152
|
+
armFromShutdown(): void {
|
|
153
|
+
if (!this.enabled || this.armed) return;
|
|
154
|
+
this.arm(SHUTDOWN_EVENT_MARKER);
|
|
155
|
+
}
|
|
156
|
+
|
|
141
157
|
setEnabled(enabled: boolean): void {
|
|
142
158
|
this.enabled = enabled;
|
|
143
159
|
if (!enabled) this.disarm();
|
|
@@ -193,11 +209,16 @@ export class QuitGuard {
|
|
|
193
209
|
// The liveness probe is best-effort: if it throws (stdin already
|
|
194
210
|
// destroyed/replaced during teardown), treat the TUI as gone and
|
|
195
211
|
// still fire. A probe that can throw must not disable the watchdog.
|
|
212
|
+
// An event-armed guard skips the probe on purpose: the TUI is still
|
|
213
|
+
// up in exactly the signal-triggered case we are covering, and the
|
|
214
|
+
// shutdown event (not rendered content) is what armed it.
|
|
196
215
|
let tuiActive = false;
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
216
|
+
if (this.armedBy !== SHUTDOWN_EVENT_MARKER) {
|
|
217
|
+
try {
|
|
218
|
+
tuiActive = this.isTuiActive?.() === true;
|
|
219
|
+
} catch {
|
|
220
|
+
tuiActive = false;
|
|
221
|
+
}
|
|
201
222
|
}
|
|
202
223
|
if (tuiActive) {
|
|
203
224
|
// A live TUI means the marker was content, not a teardown.
|
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* Problem this solves: pi's interactive `/quit` stops the TUI, then awaits
|
|
5
5
|
* `runtimeHost.dispose()` — every extension's `session_shutdown` handler,
|
|
6
6
|
* one after another, with no timeout (upstream issue #9997; still unbounded
|
|
7
|
-
* in 1.5.
|
|
7
|
+
* in 1.5.1 and on main — 1.5.1 added `await session.abort()` before the
|
|
8
|
+
* handler loop and `await settleCredentialWrites()` after it, i.e. more awaits
|
|
9
|
+
* in the same untimed chain, which makes the failure mode more likely, not
|
|
10
|
+
* less). One handler that never settles leaves the process
|
|
8
11
|
* alive at 0% CPU, the terminal already restored and the final frame
|
|
9
12
|
* reprinted: the screen looks like a frozen "exit screen" and the shell
|
|
10
13
|
* prompt never comes back. The `isShuttingDown` latch in the host then
|
|
@@ -26,7 +29,7 @@
|
|
|
26
29
|
* `<agent-dir>/pi-toolkits-quit-guard.json`.
|
|
27
30
|
*
|
|
28
31
|
* Settings file (all fields optional, defaults shown):
|
|
29
|
-
* { "enabled": true, "timeoutMs":
|
|
32
|
+
* { "enabled": true, "timeoutMs": 8000, "report": true }
|
|
30
33
|
*/
|
|
31
34
|
import { appendFileSync, existsSync, readdirSync, writeSync } from "node:fs";
|
|
32
35
|
import { join } from "node:path";
|
|
@@ -37,6 +40,8 @@ import {
|
|
|
37
40
|
MIN_TIMEOUT_MS,
|
|
38
41
|
QUIT_GUARD_FILE,
|
|
39
42
|
QUIT_GUARD_REPORT_DIR,
|
|
43
|
+
SHUTDOWN_EVENT_MARKER,
|
|
44
|
+
TERMINAL_RESTORE,
|
|
40
45
|
} from "./constants.js";
|
|
41
46
|
import { QuitGuard, type GuardFireInfo } from "./guard.js";
|
|
42
47
|
import {
|
|
@@ -78,6 +83,18 @@ function storeSharedState(state: QuitGuardState): void {
|
|
|
78
83
|
}
|
|
79
84
|
|
|
80
85
|
function fire(state: QuitGuardState, info: GuardFireInfo): void {
|
|
86
|
+
// Armed by `session_shutdown` (signal-triggered quit, or a shutdown that
|
|
87
|
+
// hung before `ui.stop()`): nothing restored the terminal, so do it here
|
|
88
|
+
// before exiting or the prompt comes back on the alternate screen, with
|
|
89
|
+
// bracketed paste on and the cursor hidden. `writeSync(1, …)` bypasses our
|
|
90
|
+
// own stdout wrapper, so these sequences cannot re-arm the guard.
|
|
91
|
+
if (info.marker === SHUTDOWN_EVENT_MARKER) {
|
|
92
|
+
try {
|
|
93
|
+
writeSync(1, TERMINAL_RESTORE);
|
|
94
|
+
} catch {
|
|
95
|
+
// Dead terminal: the report and the exit still happen.
|
|
96
|
+
}
|
|
97
|
+
}
|
|
81
98
|
const timeoutMs = state.guard.getTimeoutMs();
|
|
82
99
|
const elapsedMs = Math.round(info.elapsedMs);
|
|
83
100
|
let reportPath: string | undefined;
|
|
@@ -251,6 +268,18 @@ export function registerQuitGuard(
|
|
|
251
268
|
}
|
|
252
269
|
}
|
|
253
270
|
|
|
271
|
+
// Second trigger: the process is quitting even though the TUI has not
|
|
272
|
+
// written its teardown sequence yet. `reason === "quit"` is only emitted by
|
|
273
|
+
// the runtime's dispose() on process exit; session replacements use
|
|
274
|
+
// new/resume/fork and /reload uses reload, and none of those may arm.
|
|
275
|
+
// The same event also fires for RPC/JSON/print shutdowns. Restrict this
|
|
276
|
+
// trigger to the interactive TUI: terminal restoration must never inject
|
|
277
|
+
// escape sequences into a machine-readable stdout protocol.
|
|
278
|
+
pi.on("session_shutdown", (event, ctx) => {
|
|
279
|
+
if (event.reason !== "quit" || ctx.mode !== "tui") return;
|
|
280
|
+
state.guard.armFromShutdown();
|
|
281
|
+
});
|
|
282
|
+
|
|
254
283
|
pi.registerCommand("quit-guard", {
|
|
255
284
|
description:
|
|
256
285
|
"Quit watchdog: force-exit when pi's shutdown hangs (/quit-guard [on|off|<timeoutMs>])",
|
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
* directories (never the real agent dir).
|
|
7
7
|
*
|
|
8
8
|
* Coverage map:
|
|
9
|
-
* - arming on both teardown markers
|
|
9
|
+
* - arming on both teardown markers and on a quit `session_shutdown` event
|
|
10
|
+
* (the signal-triggered path, where the marker is never written),
|
|
11
|
+
* idempotence, re-arm after disarm;
|
|
10
12
|
* - disarming on both restart markers (TUI mode switch, Ctrl+Z resume) and
|
|
11
13
|
* on an explicit `resume()`, including the "expired timer loses to
|
|
12
14
|
* SIGCONT" race;
|
|
@@ -32,13 +34,16 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
32
34
|
import type {
|
|
33
35
|
ExtensionAPI,
|
|
34
36
|
ExtensionCommandContext,
|
|
37
|
+
ExtensionContext,
|
|
35
38
|
} from "@earendil-works/pi-coding-agent";
|
|
36
39
|
import {
|
|
37
40
|
DEFAULT_TIMEOUT_MS,
|
|
38
41
|
MAX_TIMEOUT_MS,
|
|
39
42
|
MIN_TIMEOUT_MS,
|
|
40
43
|
RESTART_MARKERS,
|
|
44
|
+
SHUTDOWN_EVENT_MARKER,
|
|
41
45
|
TEARDOWN_MARKERS,
|
|
46
|
+
TERMINAL_RESTORE,
|
|
42
47
|
} from "./constants.js";
|
|
43
48
|
import { QuitGuard, findMarker, type GuardFireInfo } from "./guard.js";
|
|
44
49
|
import { registerQuitGuard } from "./index.js";
|
|
@@ -133,6 +138,12 @@ describe("terminal markers", () => {
|
|
|
133
138
|
expect(TEARDOWN_MARKERS).toEqual(["\x1b[?2004l", "\x1b[?1049l"]);
|
|
134
139
|
expect(RESTART_MARKERS).toEqual(["\x1b[?2004h", "\x1b[?1049h"]);
|
|
135
140
|
});
|
|
141
|
+
|
|
142
|
+
it("restores paste mode, the alternate screen and the cursor on a forced exit", () => {
|
|
143
|
+
expect(TERMINAL_RESTORE).toBe(
|
|
144
|
+
"\x1b[?2004l\x1b[?1049l\x1b[?25h\x1b[0m\r\n",
|
|
145
|
+
);
|
|
146
|
+
});
|
|
136
147
|
});
|
|
137
148
|
|
|
138
149
|
describe("findMarker", () => {
|
|
@@ -305,6 +316,52 @@ describe("QuitGuard", () => {
|
|
|
305
316
|
expect(fired).toHaveLength(1);
|
|
306
317
|
});
|
|
307
318
|
|
|
319
|
+
it("arms from a quit shutdown event when no teardown was written", () => {
|
|
320
|
+
const { guard, timers, deferred, fired, advance } = makeGuard({});
|
|
321
|
+
guard.armFromShutdown();
|
|
322
|
+
expect(guard.isArmed()).toBe(true);
|
|
323
|
+
advance(1_000);
|
|
324
|
+
timers.fire();
|
|
325
|
+
deferred.flush();
|
|
326
|
+
expect(fired).toEqual([
|
|
327
|
+
{ startedAt: 0, elapsedMs: 1_000, marker: SHUTDOWN_EVENT_MARKER },
|
|
328
|
+
]);
|
|
329
|
+
expect(guard.isArmed()).toBe(false);
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
it("keeps the teardown deadline when a shutdown event arrives later", () => {
|
|
333
|
+
const { guard, timers, deferred, fired, advance } = makeGuard({});
|
|
334
|
+
guard.observeOutput("\x1b[?2004l");
|
|
335
|
+
advance(500);
|
|
336
|
+
guard.armFromShutdown(); // no-op: one arm, one timer, one deadline
|
|
337
|
+
advance(500);
|
|
338
|
+
timers.fire();
|
|
339
|
+
deferred.flush();
|
|
340
|
+
expect(fired).toEqual([
|
|
341
|
+
{ startedAt: 0, elapsedMs: 1_000, marker: "\x1b[?2004l" },
|
|
342
|
+
]);
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
it("does not arm from a shutdown event while disabled", () => {
|
|
346
|
+
const { guard } = makeGuard({});
|
|
347
|
+
guard.setEnabled(false);
|
|
348
|
+
guard.armFromShutdown();
|
|
349
|
+
expect(guard.isArmed()).toBe(false);
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
it("ignores the raw-mode probe when a shutdown event armed it", () => {
|
|
353
|
+
// The signal-triggered path hangs while the TUI is still in raw mode, so
|
|
354
|
+
// the probe would disarm exactly the case this trigger exists for.
|
|
355
|
+
const { guard, timers, deferred, fired } = makeGuard({
|
|
356
|
+
isTuiActive: () => true,
|
|
357
|
+
});
|
|
358
|
+
guard.armFromShutdown();
|
|
359
|
+
timers.fire();
|
|
360
|
+
deferred.flush();
|
|
361
|
+
expect(fired).toHaveLength(1);
|
|
362
|
+
expect(fired[0]?.marker).toBe(SHUTDOWN_EVENT_MARKER);
|
|
363
|
+
});
|
|
364
|
+
|
|
308
365
|
it("reports arm/disarm/fire transitions to the debug tap", () => {
|
|
309
366
|
const events: string[] = [];
|
|
310
367
|
const timers = fakeTimers();
|
|
@@ -622,10 +679,22 @@ function clearSharedState(): void {
|
|
|
622
679
|
delete (globalThis as unknown as Record<symbol, unknown>)[SHARED_KEY];
|
|
623
680
|
}
|
|
624
681
|
|
|
625
|
-
function fakePi(): {
|
|
682
|
+
function fakePi(): {
|
|
683
|
+
pi: ExtensionAPI;
|
|
684
|
+
command: () => CommandHandler;
|
|
685
|
+
emit: (
|
|
686
|
+
event: string,
|
|
687
|
+
payload: unknown,
|
|
688
|
+
mode?: ExtensionContext["mode"],
|
|
689
|
+
) => void;
|
|
690
|
+
} {
|
|
626
691
|
let registered: CommandHandler | undefined;
|
|
627
|
-
|
|
628
|
-
|
|
692
|
+
const handlers = new Map<
|
|
693
|
+
string,
|
|
694
|
+
Array<(payload: unknown, ctx: ExtensionContext) => void>
|
|
695
|
+
>();
|
|
696
|
+
// SAFETY: only `registerCommand` and `on` are called by the feature; the
|
|
697
|
+
// rest of the host surface is irrelevant here.
|
|
629
698
|
const pi = {
|
|
630
699
|
registerCommand: (
|
|
631
700
|
_name: string,
|
|
@@ -633,6 +702,12 @@ function fakePi(): { pi: ExtensionAPI; command: () => CommandHandler } {
|
|
|
633
702
|
): void => {
|
|
634
703
|
registered = options.handler;
|
|
635
704
|
},
|
|
705
|
+
on: (
|
|
706
|
+
name: string,
|
|
707
|
+
handler: (payload: unknown, ctx: ExtensionContext) => void,
|
|
708
|
+
): void => {
|
|
709
|
+
handlers.set(name, [...(handlers.get(name) ?? []), handler]);
|
|
710
|
+
},
|
|
636
711
|
} as unknown as ExtensionAPI;
|
|
637
712
|
return {
|
|
638
713
|
pi,
|
|
@@ -640,6 +715,11 @@ function fakePi(): { pi: ExtensionAPI; command: () => CommandHandler } {
|
|
|
640
715
|
if (!registered) throw new Error("command was not registered");
|
|
641
716
|
return registered;
|
|
642
717
|
},
|
|
718
|
+
emit: (event, payload, mode = "tui") => {
|
|
719
|
+
// SAFETY: event handlers under test only read `mode` from the context.
|
|
720
|
+
const ctx = { mode } as ExtensionContext;
|
|
721
|
+
for (const handler of handlers.get(event) ?? []) handler(payload, ctx);
|
|
722
|
+
},
|
|
643
723
|
};
|
|
644
724
|
}
|
|
645
725
|
|
|
@@ -693,6 +773,43 @@ describe("/quit-guard command", () => {
|
|
|
693
773
|
expect(existsSync(settings)).toBe(false);
|
|
694
774
|
});
|
|
695
775
|
|
|
776
|
+
it("arms on session_shutdown only for an interactive quit", () => {
|
|
777
|
+
const { dir } = setup();
|
|
778
|
+
const debugPath = join(dir, "guard-debug.jsonl");
|
|
779
|
+
process.env.PI_QUIT_GUARD_DEBUG = debugPath;
|
|
780
|
+
try {
|
|
781
|
+
const { pi, command, emit } = fakePi();
|
|
782
|
+
const { ctx } = fakeCtx();
|
|
783
|
+
registerQuitGuard(pi, { agentDir: dir });
|
|
784
|
+
// Session replacement and reload tear a session down without exiting.
|
|
785
|
+
emit("session_shutdown", { type: "session_shutdown", reason: "reload" });
|
|
786
|
+
emit("session_shutdown", {
|
|
787
|
+
type: "session_shutdown",
|
|
788
|
+
reason: "new",
|
|
789
|
+
targetSessionFile: "/tmp/next.jsonl",
|
|
790
|
+
});
|
|
791
|
+
expect(readFileSync(debugPath, "utf8")).not.toContain("arm ");
|
|
792
|
+
// RPC/JSON/print also dispose with reason quit, but stdout there is a
|
|
793
|
+
// data protocol, not a terminal: the event trigger must stay inert.
|
|
794
|
+
for (const mode of ["rpc", "json", "print"] as const) {
|
|
795
|
+
emit(
|
|
796
|
+
"session_shutdown",
|
|
797
|
+
{ type: "session_shutdown", reason: "quit" },
|
|
798
|
+
mode,
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
expect(readFileSync(debugPath, "utf8")).not.toContain("arm ");
|
|
802
|
+
emit("session_shutdown", { type: "session_shutdown", reason: "quit" });
|
|
803
|
+
expect(readFileSync(debugPath, "utf8")).toContain(
|
|
804
|
+
`arm ${SHUTDOWN_EVENT_MARKER}`,
|
|
805
|
+
);
|
|
806
|
+
// Disarm so the test leaves no pending deadline behind.
|
|
807
|
+
void command()("off", ctx);
|
|
808
|
+
} finally {
|
|
809
|
+
delete process.env.PI_QUIT_GUARD_DEBUG;
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
|
|
696
813
|
it("persists an off switch and turns the guard inert", async () => {
|
|
697
814
|
const { dir, settings } = setup();
|
|
698
815
|
const { pi, command } = fakePi();
|
|
@@ -167,7 +167,7 @@ export function collectHangReport(
|
|
|
167
167
|
marker: input.marker,
|
|
168
168
|
uptimeSeconds: attempt(() => Math.round(proc.uptime()), 0),
|
|
169
169
|
// `process.cwd()` throws ENOENT when the directory was removed during
|
|
170
|
-
// the session (a startup crash pi itself guards against in 1.5.
|
|
170
|
+
// the session (a startup crash pi itself guards against in 1.5.1). The
|
|
171
171
|
// report is written on the exit path, so it must survive that.
|
|
172
172
|
cwd: options.cwd ?? attempt(() => proc.cwd(), UNKNOWN_CWD),
|
|
173
173
|
argv: attempt(
|
|
@@ -21,7 +21,7 @@ import type { KeyId } from "@earendil-works/pi-tui";
|
|
|
21
21
|
/**
|
|
22
22
|
* Stash hotkey.
|
|
23
23
|
*
|
|
24
|
-
* Compatibility rationale (verified against pi 0.99.0–1.5.
|
|
24
|
+
* Compatibility rationale (verified against pi 0.99.0–1.5.1 keybindings, live
|
|
25
25
|
* matchesKey probes and terminal/OS behavior):
|
|
26
26
|
* - pi: no default binding for ctrl+alt+<letter> (only ctrl+alt+] is taken);
|
|
27
27
|
* extension shortcuts dispatch first while the editor is focused
|
package/src/lib/model-config.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* Types are derived from pi-coding-agent's own exports (ModelRegistry)
|
|
7
7
|
* rather than imported from @earendil-works/pi-ai: pi-ai's index.d.ts (1.2.0
|
|
8
|
-
* through 1.5.
|
|
8
|
+
* through 1.5.1 alike) re-exports `Model`/`Api` via extensioned
|
|
9
9
|
* `./types.ts` specifiers, which tsc 5.9 bundler resolution substitutes to
|
|
10
10
|
* `.d.ts` but some tsserver builds do not. Deriving from ModelRegistry keeps
|
|
11
11
|
* every resolver in agreement with the exact type
|
package/src/lib/model-picker.ts
CHANGED
|
@@ -9,12 +9,15 @@
|
|
|
9
9
|
*
|
|
10
10
|
* The component is driven through a small ModelRuntime facade backed by
|
|
11
11
|
* ctx.modelRegistry (pi's extension-facing wrapper). SAFETY: verified
|
|
12
|
-
* against pi 1.2.0–1.5.
|
|
12
|
+
* against pi 1.2.0–1.5.1 dist (modes/interactive/components/model-selector.js +
|
|
13
13
|
* model-catalog-refresh.js) — the component only calls getAvailableSnapshot,
|
|
14
14
|
* getModel and getError on modelRuntime (plus refresh, which ModelRegistry
|
|
15
15
|
* provides) across that whole span. 1.5.0 changed the selector's rendering
|
|
16
16
|
* and key handling (page keys, disambiguating model names, viewport-input
|
|
17
|
-
* capture) but not the runtime surface this facade implements.
|
|
17
|
+
* capture) but not the runtime surface this facade implements, and 1.5.1 only
|
|
18
|
+
* changed how a background refresh re-applies the filter (a second
|
|
19
|
+
* `preferredModel` argument that keeps the highlighted row, #9109) — still no
|
|
20
|
+
* new runtime call.
|
|
18
21
|
*
|
|
19
22
|
* `current` is passed as the component's currentModel: the built-in selector
|
|
20
23
|
* preselects, ✓-marks and sorts-first its currentModel, so one Enter accepts
|
|
@@ -43,10 +46,10 @@ function modelRuntimeFacade(ctx: ExtensionContext): ModelRuntime {
|
|
|
43
46
|
refresh: (options?: { signal?: AbortSignal }) =>
|
|
44
47
|
ctx.modelRegistry.refresh(options),
|
|
45
48
|
};
|
|
46
|
-
// SAFETY: the selector only touches the four members above (pi 1.0–1.5
|
|
47
|
-
// model-selector.js; the 1.5.0 rendering/page-key changes
|
|
48
|
-
// call); everything else on
|
|
49
|
-
// component.
|
|
49
|
+
// SAFETY: the selector only touches the four members above (pi 1.0–1.5.1
|
|
50
|
+
// model-selector.js; the 1.5.0 rendering/page-key changes and the 1.5.1
|
|
51
|
+
// refresh-selection change add no runtime call); everything else on
|
|
52
|
+
// ModelRuntime is never reached from this component.
|
|
50
53
|
return facade as unknown as ModelRuntime;
|
|
51
54
|
}
|
|
52
55
|
|