dsh-question-timeout-protection 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # dsh-question-timeout-protection
4
4
 
5
- [![Version](https://img.shields.io/badge/Version-0.1.2-green)](https://github.com/JularDepick/dsh-question-timeout-protection/releases)
5
+ [![Version](https://img.shields.io/badge/Version-0.1.4-green)](https://github.com/JularDepick/dsh-question-timeout-protection/releases)
6
6
  [![Copyright](https://img.shields.io/badge/Copyright-JularDepick-0066AA)](./COPYRIGHT)
7
7
  [![License](https://img.shields.io/badge/License-Apache--2.0-yellow)](./LICENSE)
8
8
 
@@ -36,7 +36,7 @@ dsh 默认的提问是阻塞式的: 模型问完就一直等, 你离开一会儿
36
36
 
37
37
  ### 前置条件
38
38
 
39
- - dsh 版本在 `>=0.2.1-rc.1 <=0.2.2-rc.2` 之内, 不满足会被安装与启动阶段拒绝
39
+ - dsh 版本在 `>=0.2.1-rc.1 <0.2.3-rc.1` 之内, 不满足会被安装与启动阶段拒绝
40
40
  - Node.js >= 20
41
41
 
42
42
  ### 方式一: 从 npm 安装
@@ -47,7 +47,7 @@ dsh 原生支持从 npm 安装插件:
47
47
  dsh plugin --profile <profile> add dsh-question-timeout-protection
48
48
  ```
49
49
 
50
- npm 上的 latest 目前是 0.1.1, 它声明的 dsh 上限是 0.2.2-rc.1, 因此在 0.2.2-rc.2 上会被安装与启动阶段拒绝. 想用本版本(0.1.2)请走下面的方式二至方式四; latest 指向 0.1.2 后, 上面的命令即可直接安装本版本.
50
+ 按包名安装默认取 npm 上 latest 标签指向的版本. 0.1.2 声明的 dsh 上限是 `0.2.2-rc.2`, 在 dsh `0.2.2-rc.3` 起的宿主上会被安装与启动阶段拒绝; 需要固定版本时用 `dsh plugin --profile <profile> add dsh-question-timeout-protection@<版本>`. 本版本 0.1.4 的上限是 `<0.2.3-rc.1`, 也可以按下面的方式二至方式四从源码或 tarball 安装.
51
51
 
52
52
  ### 方式二: 从源码构建后安装
53
53
 
@@ -60,7 +60,7 @@ dsh plugin --profile <profile> add ./release/<tarball>
60
60
  dsh plugin --profile <profile> add <绝对路径>
61
61
  ```
62
62
 
63
- `pnpm pack` 会先构建, 完成后把 tarball 移入仓库根目录的 `release/`, 文件名形如 `dsh-question-timeout-protection-0.1.2.tgz`. 沙箱内生命周期脚本被拦截时改用 `pnpm run pack:release`, 产物相同. `add` 的路径要以 `./` 或 `../` 开头才会按你执行命令的目录解析, 不带前缀会被当成包名去查注册表.
63
+ `pnpm pack` 会先构建, 完成后把 tarball 移入仓库根目录的 `release/`, 文件名形如 `dsh-question-timeout-protection-0.1.4.tgz`. 沙箱内生命周期脚本被拦截时改用 `pnpm run pack:release`, 产物相同. `add` 的路径要以 `./` 或 `../` 开头才会按你执行命令的目录解析, 不带前缀会被当成包名去查注册表.
64
64
 
65
65
  ### 方式三: 直接从 GitHub 源码安装
66
66
 
@@ -106,13 +106,13 @@ dsh plugin --profile <profile> add <绝对路径>
106
106
 
107
107
  倒计时右侧的「无限等待」按钮, 点击后本次提问不再有截止时间, 倒计时冻结为「已暂停」, 直到你提交才结束.
108
108
 
109
- 这个动作需要服务端确认登记成功才会生效, 因此点击后要等回执. 如果状态通道不可用, 按钮不会生效, 卡片会回到计时状态并在倒计时位置显示「无法无限等待」.
109
+ 点击后界面立即冻结倒计时, 同时向服务端登记这次「无限等待」; 登记失败或回执超时时撤回冻结, 卡片回到计时状态, 倒计时位置显示「无法无限等待」.
110
110
 
111
111
  ### 自动无限等待
112
112
 
113
113
  工具栏模型选择控件左侧有一个常开开关「问答自动无限等待」. 开启后, 每一条新提问都自动进入无限等待, 正在等待的那条也会立刻冻结, 效果与手动点一次「无限等待」相同.
114
114
 
115
- 开关状态存在浏览器本地, 刷新后保留. 关闭开关只影响之后的新提问, 已经冻结的提问不会恢复倒计时, 仍由你提交结束.
115
+ 开关状态存在浏览器本地, 刷新后保留. 关闭开关只影响之后的新提问, 已经冻结的提问不会恢复倒计时, 仍由你提交结束. 多个标签页开着同一会话时, 在其中一个页面切换开关, 其他页面会在下一次界面扫描时跟上, 正在等待的提问也会随之冻结.
116
116
 
117
117
  这个开关只在卡片增强与无限等待都开启时出现.
118
118
 
@@ -151,7 +151,7 @@ dsh plugin --profile <profile> add <绝对路径>
151
151
 
152
152
  | 项目 | 版本 |
153
153
  |:---:|:---:|
154
- | dsh | `>=0.2.1-rc.1 <=0.2.2-rc.2` |
154
+ | dsh | `>=0.2.1-rc.1 <0.2.3-rc.1` |
155
155
  | Node.js | >= 20 |
156
156
 
157
157
  宿主 dsh 自身的 Node.js 要求以对应版本的发行说明为准.
@@ -198,7 +198,7 @@ dsh plugin --profile <profile> add <绝对路径>
198
198
 
199
199
  **依赖宿主提问投影**
200
200
 
201
- 客户端靠宿主 sessions 服务的 userQuestions 投影判断提问是否进入 continued 态, 草稿上报, 超时收尾与气泡都由它驱动. 该服务缺失或接口改名时插件按会话各打一条 console.warn: 倒计时与卡片装饰仍在, 但草稿不上报, 超时收尾不执行, 气泡不出现.
201
+ 客户端靠宿主 sessions 服务的 userQuestions 投影判断提问是否进入 continued 态, 草稿上报, 超时收尾与气泡都由它驱动. 该服务缺失或接口改名时插件按会话各打一条 console.warn: 倒计时与卡片装饰仍在, 卡片仍处于宿主等待状态时草稿照常上报并随工具结果回到模型, 但超时收尾不执行, 气泡不出现.
202
202
 
203
203
  **会话订阅上限**
204
204
 
@@ -214,7 +214,11 @@ dsh plugin --profile <profile> add <绝对路径>
214
214
 
215
215
  **界面语言**
216
216
 
217
- 宿主 0.2.2-rc.1 起提供 8 种界面语言, 插件只识别中文与英文标签. 其他语言界面下倒计时, 无限等待按钮与工具栏开关不出现, 插件自绘的气泡与配置页文案回退英文. ja 的「回答」与中文同形会被隐藏, 但 ja 的等待文案仍会保留, 与被收起卡片的状态不一致; 其余语言下宿主的「回答」入口与等待文案大多仍然可见. ja 下空草稿超时不会出现插件气泡, 宿主的入口又已按文案隐藏, 因此这一轮没有可点的回看入口. 卡片关闭在这些语言下退化为隐藏类, 提交按钮不锁定.
217
+ 宿主 0.2.2-rc.1 起提供 8 种界面语言, 插件只识别中文与英文标签. 其他语言界面下倒计时, 无限等待按钮与工具栏开关不出现, 插件自绘的气泡与配置页文案回退英文. ja 的「回答」与中文同形会被隐藏, 但 ja 的等待文案仍会保留, 与被收起卡片的状态不一致; 其余语言下宿主的「回答」入口与等待文案大多仍然可见. ja 下空草稿超时不会出现插件气泡, 宿主的入口又已按文案隐藏, 因此这一轮没有可点的回看入口. 卡片关闭在这些语言下退化为隐藏类: 输入框被禁用, 但提交, 下一题与跳过按钮因标签不匹配不会被锁定(卡片已整体隐藏, 看不到这些状态).
218
+
219
+ **PTC 模式下受外层程序预算约束**
220
+
221
+ 模型在 `run_code`(PTC 模式)里调用提问工具时, 这一轮提问的寿命受外层程序的 elapsed-time budget 约束: 预算到期时宿主硬停程序并中止在途的提问, 界面上的倒计时会中途消失, 草稿也来不及交给模型. 插件在提问期间登记外层预算, 把等待收敛到「剩余预算减去收尾余量」之内: 提问在预算到期前自己按超时结算, 草稿照常随 pending 结果交给模型, 倒计时也按收敛后的时长显示. 扣除收尾余量后可用时长不足两秒时不开卡片, 直接按预算不足结算并告知模型. 「无限等待」不能突破外层预算: 冻结后的提问仍会在预算到期时结束, 只是草稿会被保留. 被中断的提问在工具行上留下只读气泡, 可回看中断那一刻的草稿. run_code 里再嵌套一层 run_code 时按内层预算收敛; 预算起点取程序真正开始派发的时刻, 前置包装造成的延迟不计入; 草稿随 pending 结果进入上下文时按单题与整轮上限截断, 截断会在同一条结果里说明, 避免超长草稿被宿主的工具结果裁剪整段吃掉.
218
222
 
219
223
  **其他**
220
224
 
@@ -226,7 +230,7 @@ dsh plugin --profile <profile> add <绝对路径>
226
230
  - 草稿按题合并三处来源, 优先级为宿主持久化记录, 当前显示题的实时值, 插件自己的快照; 读实时值时已选标签取的是宿主给读屏用的文案, 其中的「(推荐)」这类后缀可能被省略
227
231
  - 桌面端(macOS)自 dsh 0.2.2-rc.2 起只在带 `data-window-drag` 的页头行内允许拖动窗口, 带 `data-window-drag-controls` 的容器里的控件由宿主自动排除拖动; 覆盖拖动行的自定义浮层要自身声明 `data-window-drag-exclude` 才可交互, 顶部还留了 `--dsh-frame-top-clearance` 的预留带. 插件的草稿浮层挂在 body 上, 既没有声明拖动排除也不读预留带, 因此桌面端贴近窗口顶部时可能落进预留带; 浮层内没有可点控件, 影响限于位置; 网页客户端不受影响
228
232
  - 注入给模型的超时说明目前只有中文, 英文界面下模型收到的仍是中文说明
229
- - 草稿超过单次上报上限 256 KiB 时界面显示「草稿过长, 未送达」, 这一条不计入连续失败次数; 连续失败三次后该轮判定通道不可用, 插件不再接管, 卡片交还宿主继续可作答
233
+ - 草稿超过单次上报上限 256 KiB 时界面显示「草稿过长, 未送达」, 这一条不计入连续失败次数, 并按固定间隔(约 5 秒)自动重试, 删减内容后会恢复上报; 连续失败三次后该轮判定通道不可用, 插件不再接管, 卡片交还宿主继续可作答
230
234
 
231
235
  ## 更新与卸载
232
236
 
package/README_en-US.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # dsh-question-timeout-protection
4
4
 
5
- [![Version](https://img.shields.io/badge/Version-0.1.2-green)](https://github.com/JularDepick/dsh-question-timeout-protection/releases)
5
+ [![Version](https://img.shields.io/badge/Version-0.1.4-green)](https://github.com/JularDepick/dsh-question-timeout-protection/releases)
6
6
  [![Copyright](https://img.shields.io/badge/Copyright-JularDepick-0066AA)](./COPYRIGHT)
7
7
  [![License](https://img.shields.io/badge/License-Apache--2.0-yellow)](./LICENSE)
8
8
 
@@ -36,7 +36,7 @@ This plugin adds three things: you can see how long is left, you can pause the w
36
36
 
37
37
  ### Requirements
38
38
 
39
- - dsh within `>=0.2.1-rc.1 <=0.2.2-rc.2`; installation and startup refuse anything outside it
39
+ - dsh within `>=0.2.1-rc.1 <0.2.3-rc.1`; installation and startup refuse anything outside it
40
40
  - Node.js >= 20
41
41
 
42
42
  ### Option A: install from npm
@@ -47,7 +47,7 @@ dsh installs plugins from npm natively:
47
47
  dsh plugin --profile <profile> add dsh-question-timeout-protection
48
48
  ```
49
49
 
50
- The npm latest tag currently points at 0.1.1, which declares dsh support only up to 0.2.2-rc.1, so installation and startup reject it on 0.2.2-rc.2. For this version (0.1.2) use Options B to D below; once latest points at 0.1.2 the command above installs this version directly.
50
+ Installing by package name takes whatever the npm latest tag points at. Version 0.1.2 declares dsh support only up to `0.2.2-rc.2`, so installation and startup reject it on dsh `0.2.2-rc.3` and later; pin a version with `dsh plugin --profile <profile> add dsh-question-timeout-protection@<version>`. This version (0.1.4) supports up to `<0.2.3-rc.1`, and Options B to D below install it from source or a tarball.
51
51
 
52
52
  ### Option B: build from source
53
53
 
@@ -60,7 +60,7 @@ dsh plugin --profile <profile> add ./release/<tarball>
60
60
  dsh plugin --profile <profile> add <absolute path>
61
61
  ```
62
62
 
63
- `pnpm pack` builds first, then moves the tarball into `release/` at the repository root under a name like `dsh-question-timeout-protection-0.1.2.tgz`. Where a sandbox blocks lifecycle scripts, use `pnpm run pack:release` for the same artifact. A path passed to `add` is resolved against your current directory only when it starts with `./` or `../`; otherwise it is treated as a package name and looked up in the registry.
63
+ `pnpm pack` builds first, then moves the tarball into `release/` at the repository root under a name like `dsh-question-timeout-protection-0.1.4.tgz`. Where a sandbox blocks lifecycle scripts, use `pnpm run pack:release` for the same artifact. A path passed to `add` is resolved against your current directory only when it starts with `./` or `../`; otherwise it is treated as a package name and looked up in the registry.
64
64
 
65
65
  ### Option C: install from the GitHub source
66
66
 
@@ -106,13 +106,13 @@ Historical questions and settled answers never show a countdown.
106
106
 
107
107
  The "Wait indefinitely" button sits next to the countdown. Clicking it removes the deadline for this question and freezes the countdown as "Paused" until you submit.
108
108
 
109
- The action takes effect only after the server confirms the registration, so a click briefly waits for that reply. If the state channel is unavailable the button does not take effect: the card returns to counting and the countdown slot reads "Cannot wait indefinitely".
109
+ Clicking it freezes the countdown immediately and registers the wait with the server; if that registration fails or the reply times out the freeze is withdrawn, the card returns to counting and the countdown slot reads "Cannot wait indefinitely".
110
110
 
111
111
  ### Auto wait indefinitely
112
112
 
113
113
  The composer toolbar carries an "Auto wait indefinitely" switch to the left of the model selector. When on, every new question enters indefinite wait automatically, and a question already waiting freezes right away, exactly as if you had clicked "Wait indefinitely" once.
114
114
 
115
- The switch state lives in browser storage and survives a refresh. Turning it off affects only later questions: frozen questions stay frozen and end when you submit.
115
+ The switch state lives in browser storage and survives a refresh. Turning it off affects only later questions: frozen questions stay frozen and end when you submit. With several tabs on the same session, toggling the switch in one page is picked up by the others on their next scan, and a question that is still waiting freezes too.
116
116
 
117
117
  The switch appears only while card enhancements and indefinite wait are both on.
118
118
 
@@ -134,7 +134,7 @@ With this off, the plugin only withdraws the card and hands the model no draft.
134
134
 
135
135
  ### Configuration
136
136
 
137
- The config page sits at the **top of the plugin detail view**, not inside "Components". Only "Inject into context" can be changed, and a toggle writes immediately without any save or refresh. Keep the draft in the UI and the three fixed features below are listed as fixed rows for reference; the page offers no switches for them.
137
+ The config page sits at the **top of the plugin detail view**, not inside "Components". Only "Inject into context" can be changed, and a toggle writes immediately without any save or refresh. The page lists "keep the draft in the UI" and the three fixed features below as fixed rows for reference; none of them has a switch.
138
138
 
139
139
  | Option | Values | Default | UI | Description |
140
140
  |:---:|:---:|:---:|:---:|:---:|
@@ -151,7 +151,7 @@ The last two are not exposed in the UI; write them into this plugin's row under
151
151
 
152
152
  | Item | Version |
153
153
  |:---:|:---:|
154
- | dsh | `>=0.2.1-rc.1 <=0.2.2-rc.2` |
154
+ | dsh | `>=0.2.1-rc.1 <0.2.3-rc.1` |
155
155
  | Node.js | >= 20 |
156
156
 
157
157
  The Node.js requirement of the host dsh itself follows the release notes of the matching version.
@@ -198,7 +198,7 @@ Cards and tool rows are located through host class-name suffixes, `data-question
198
198
 
199
199
  **Depends on the host question projection**
200
200
 
201
- The client relies on the userQuestions projection of the host sessions service to tell whether a question entered the continued state; draft reporting, the timeout wrap-up and the bubble all follow it. If that service is missing or the interface is renamed the plugin logs one console.warn per session: the countdown and card decoration stay, but no draft is reported, the wrap-up does not run and no bubble appears.
201
+ The client relies on the userQuestions projection of the host sessions service to tell whether a question entered the continued state; draft reporting, the timeout wrap-up and the bubble all follow it. If that service is missing or the interface is renamed the plugin logs one console.warn per session: the countdown and card decoration stay, and while the card still shows the host waiting state the draft is still reported and still rides the tool result back to the model, but the wrap-up does not run and no bubble appears.
202
202
 
203
203
  **Session subscription cap**
204
204
 
@@ -214,7 +214,11 @@ Both share one token-protected channel mounted on the host's own HTTP service, s
214
214
 
215
215
  **UI languages**
216
216
 
217
- dsh 0.2.2-rc.1 ships eight UI languages while the plugin recognises Chinese and English labels only. Under other locales the countdown, the wait-indefinitely button and the toolbar switch are not rendered, and the plugin's own bubble and config page fall back to English. The Japanese "回答" is identical to Chinese and is hidden, while the Japanese wait text stays visible and contradicts the withdrawn card; in the remaining locales the host answer entry and its wait text mostly stay visible. Under Japanese, a timeout with an empty draft produces no plugin bubble while the host entry is already hidden by its label, so that round offers no entry to reopen. Card dismissal degrades to CSS hiding there and submit buttons stay enabled.
217
+ dsh 0.2.2-rc.1 ships eight UI languages while the plugin recognises Chinese and English labels only. Under other locales the countdown, the wait-indefinitely button and the toolbar switch are not rendered, and the plugin's own bubble and config page fall back to English. The Japanese "回答" is identical to Chinese and is hidden, while the Japanese wait text stays visible and contradicts the withdrawn card; in the remaining locales the host answer entry and its wait text mostly stay visible. Under Japanese, a timeout with an empty draft produces no plugin bubble while the host entry is already hidden by its label, so that round offers no entry to reopen. Card dismissal degrades to CSS hiding there: the inputs are disabled, but the submit, next and skip buttons are not locked because their labels do not match (the whole card is hidden, so those states are not visible).
218
+
219
+ **Bounded by the enclosing program budget in PTC mode**
220
+
221
+ When the model asks from inside `run_code` (PTC mode), that question lives only as long as the enclosing program's elapsed-time budget: on expiry the host stops the program hard and aborts the in-flight question, so the on-screen countdown disappears mid-way and the draft never reaches the model. The plugin records the enclosing budget while the question is live and shrinks its wait to "remaining budget minus the settle margin": the question settles itself as a timeout before the budget expires, the draft still rides the pending result back to the model, and the countdown shows the shrunk duration. When the usable time left after the settle margin is under two seconds no card is opened; the call settles immediately as budget-insufficient and the model is told so. Indefinite wait cannot outlive the enclosing budget: a frozen question still ends when the budget expires, though its draft is kept. An interrupted question leaves a read-only bubble on the tool row so the draft as it stood at that moment can still be read. A run_code nested inside another run_code shrinks the wait to the inner budget; the budget clock starts when the program is actually dispatched, so latency from earlier wrappers does not count against it; when the draft rides the pending result back to the model it is capped per question and per round, and the same result says so, so an oversized draft is not swallowed whole by the host's tool-result pruning.
218
222
 
219
223
  **Other**
220
224
 
@@ -226,7 +230,7 @@ dsh 0.2.2-rc.1 ships eight UI languages while the plugin recognises Chinese and
226
230
  - The draft is merged per question from three sources in this order: the host's persisted record, the live value of the question on screen, then the plugin's own snapshot; when the live value is read, selected labels come from the host's screen-reader text, which may drop suffixes such as "(Recommended)"
227
231
  - On the macOS desktop app, dsh 0.2.2-rc.2 allows window dragging only inside header rows carrying `data-window-drag`, and the host automatically excludes drag on controls inside a `data-window-drag-controls` container; a custom overlay covering a drag row must declare `data-window-drag-exclude` to stay interactive, and `--dsh-frame-top-clearance` reserves a strip at the top. The plugin's draft panel is attached to the body and declares neither, so near the top of the window it may fall into the reserved strip. The panel holds no clickable controls, so the effect is positional only; the web client is unaffected
228
232
  - The timeout notice injected for the model is Chinese-only, so on an English UI the model still receives Chinese text
229
- - A draft over the 256 KiB per-report limit makes the UI read "Draft too large; not delivered", which does not count towards consecutive failures; after three consecutive failures that question is judged channel-unavailable, the plugin stops taking it over and the card returns to the host and stays answerable
233
+ - A draft over the 256 KiB per-report limit makes the UI read "Draft too large; not delivered", which does not count towards consecutive failures and retries at a fixed interval (about five seconds), so trimming the text restores reporting; after three consecutive failures that question is judged channel-unavailable, the plugin stops taking it over and the card returns to the host and stays answerable
230
234
 
231
235
  ## Update and uninstall
232
236
 
package/dist/client.js CHANGED
@@ -188,6 +188,10 @@ const DRAFT_PANEL_EMPTY_EN = "No option was selected and no text had been entere
188
188
  const DRAFT_PANEL_UNANSWERED_ZH = "未作答";
189
189
  /** 只读草稿面板里某题没有作答时的提示(英文) */
190
190
  const DRAFT_PANEL_UNANSWERED_EN = "Not answered";
191
+ /** 工具行根节点的状态属性(宿主 ToolRow 的 data-state) */
192
+ const TOOL_ROW_STATE_ATTRIBUTE = "data-state";
193
+ /** 视为提问已被中断的宿主工具行状态: 失败与中止都不再有可作答的卡片 */
194
+ const TOOL_ROW_FAILED_STATES = ["error", "stopped"];
191
195
  // src/locale-core.ts
192
196
  function normalizeLocale(locale) {
193
197
  const raw = locale.trim().toLowerCase().replace(/_/g, "-");
@@ -356,7 +360,7 @@ function parseCardKey(key) {
356
360
  if (!key.startsWith("question:")) return void 0;
357
361
  const rest = key.slice(9);
358
362
  const split = rest.indexOf(":");
359
- if (split <= 0) return void 0;
363
+ if (split <= 0 || split + 1 >= rest.length) return void 0;
360
364
  return {
361
365
  sessionId: rest.slice(0, split),
362
366
  callId: rest.slice(split + 1)
@@ -377,6 +381,16 @@ function parseRemainingSeconds(text) {
377
381
  if (matched !== null) return Number(matched[1]);
378
382
  }
379
383
  }
384
+ function hostStillWaiting(card) {
385
+ for (const element of Array.from(card.querySelectorAll(WAIT_STATUS_SELECTOR))) {
386
+ const text = (element.textContent ?? "").trim();
387
+ if (text === "") continue;
388
+ if (parseRemainingSeconds(text) !== void 0) return true;
389
+ if (PAUSED_TEXT_PATTERNS.some((pattern) => pattern.test(text))) return true;
390
+ if (HOST_WAIT_PATTERNS.some((pattern) => text.includes(pattern))) return true;
391
+ }
392
+ return false;
393
+ }
380
394
  function readAutoInfinite() {
381
395
  try {
382
396
  return window.localStorage.getItem(AUTO_INFINITE_STORAGE_KEY) === "on";
@@ -538,7 +552,9 @@ function mergeDrafts(host, live, snapshot, count, liveIndex) {
538
552
  const merged = [];
539
553
  for (let i = 0; i < count; i += 1) {
540
554
  const hostItem = host?.[i];
541
- if (hostItem !== void 0) {
555
+ const liveItem = live?.[i];
556
+ const liveUsable = i === liveIndex && liveItem !== void 0 && hasItemContent(liveItem);
557
+ if (hostItem !== void 0 && !(liveUsable && !hasItemContent(hostItem))) {
542
558
  merged.push({
543
559
  selected: [...hostItem.selected],
544
560
  custom: hostItem.custom,
@@ -546,8 +562,7 @@ function mergeDrafts(host, live, snapshot, count, liveIndex) {
546
562
  });
547
563
  continue;
548
564
  }
549
- const liveItem = live?.[i];
550
- if (i === liveIndex && liveItem !== void 0 && hasItemContent(liveItem)) {
565
+ if (liveUsable && liveItem !== void 0) {
551
566
  merged.push({
552
567
  selected: [...liveItem.selected],
553
568
  custom: liveItem.custom,
@@ -711,6 +726,8 @@ function installQuestionTimeoutAdapter(ctx, source) {
711
726
  const callActive = /* @__PURE__ */ new Set();
712
727
  const callTouchedAt = /* @__PURE__ */ new Map();
713
728
  const draftTooLarge = /* @__PURE__ */ new Set();
729
+ const badCallIdWarned = /* @__PURE__ */ new Set();
730
+ const interrupted = /* @__PURE__ */ new Set();
714
731
  const draftTooLargeAt = /* @__PURE__ */ new Map();
715
732
  const callSessions = /* @__PURE__ */ new Map();
716
733
  const readLiveSelected = (card, callId) => {
@@ -755,6 +772,8 @@ function installQuestionTimeoutAdapter(ctx, source) {
755
772
  for (const id of draftTooLarge.keys()) ids.add(id);
756
773
  for (const id of draftTooLargeAt.keys()) ids.add(id);
757
774
  for (const id of dismissedCallIds.keys()) ids.add(id);
775
+ for (const id of interrupted.keys()) ids.add(id);
776
+ for (const id of badCallIdWarned.keys()) ids.add(id);
758
777
  for (const id of optionInteractions.keys()) ids.add(id);
759
778
  return [...ids];
760
779
  };
@@ -780,7 +799,8 @@ function installQuestionTimeoutAdapter(ctx, source) {
780
799
  draftTooLarge.delete(callId);
781
800
  draftTooLargeAt.delete(callId);
782
801
  dismissedCallIds.delete(callId);
783
- lastDrafts.delete(callId);
802
+ interrupted.delete(callId);
803
+ badCallIdWarned.delete(callId);
784
804
  };
785
805
  const pruneCallStates = () => {
786
806
  const now = Date.now();
@@ -799,6 +819,11 @@ function installQuestionTimeoutAdapter(ctx, source) {
799
819
  if (oldestId === void 0) break;
800
820
  forgetCall(oldestId);
801
821
  }
822
+ for (const warned of [subscribeWarned, evaluateWarned]) while (warned.size > 64) {
823
+ const oldest = warned.keys().next();
824
+ if (oldest.done) break;
825
+ warned.delete(oldest.value);
826
+ }
802
827
  };
803
828
  const pruneDrafts = () => {
804
829
  while (drafts.size > 200) {
@@ -1008,6 +1033,7 @@ function installQuestionTimeoutAdapter(ctx, source) {
1008
1033
  card.classList.add(HIDDEN_CONTROL_CLASS);
1009
1034
  };
1010
1035
  const restoreCard = (card) => {
1036
+ if (card.getAttribute(CARD_DISMISSED_ATTRIBUTE) !== null) return;
1011
1037
  card.classList.remove(HIDDEN_CONTROL_CLASS);
1012
1038
  for (const element of Array.from(card.querySelectorAll("." + HIDDEN_CONTROL_CLASS))) element.classList.remove(HIDDEN_CONTROL_CLASS);
1013
1039
  for (const element of Array.from(card.querySelectorAll("[data-dqtp-host-wait]"))) element.removeAttribute(HIDDEN_WAIT_ATTRIBUTE);
@@ -1160,6 +1186,16 @@ function installQuestionTimeoutAdapter(ctx, source) {
1160
1186
  if (current !== void 0) decorateCard(current, identity);
1161
1187
  return;
1162
1188
  }
1189
+ if (reply.reason === "bad-call-id") {
1190
+ paused.delete(identity.callId);
1191
+ if (!badCallIdWarned.has(identity.callId)) {
1192
+ badCallIdWarned.add(identity.callId);
1193
+ console.warn("[question-timeout-protection] 调用标识不符合通道格式, 「无限等待」无法登记");
1194
+ }
1195
+ const badIdCard = findCard(identity);
1196
+ if (badIdCard !== void 0) decorateCard(badIdCard, identity);
1197
+ return;
1198
+ }
1163
1199
  paused.delete(identity.callId);
1164
1200
  syncUnavailable.add(identity.callId);
1165
1201
  console.warn("[question-timeout-protection] 「无限等待」状态上报失败, 本次问答改由宿主原版处理");
@@ -1234,9 +1270,11 @@ function installQuestionTimeoutAdapter(ctx, source) {
1234
1270
  note.textContent = pick(DRAFT_PANEL_NOTE_ZH, DRAFT_PANEL_NOTE_EN);
1235
1271
  const body = document.createElement("div");
1236
1272
  body.className = "dqtp-draft-body";
1237
- const blocks = draft.questions.map((question, index) => {
1273
+ const blockCount = Math.max(draft.questions.length, draft.items.length);
1274
+ const blocks = Array.from({ length: blockCount }, (_, index) => {
1275
+ const question = draft.questions[index];
1238
1276
  const item = draft.items[index] ?? emptyItem();
1239
- const heading = (question.header ?? question.question ?? "").trim();
1277
+ const heading = (question?.header ?? question?.question ?? "").trim();
1240
1278
  const content = hasItemContent(item) ? composeItem(item) : pick(DRAFT_PANEL_UNANSWERED_ZH, DRAFT_PANEL_UNANSWERED_EN);
1241
1279
  return (heading === "" ? "" : heading + "\n") + content;
1242
1280
  });
@@ -1295,13 +1333,36 @@ function installQuestionTimeoutAdapter(ctx, source) {
1295
1333
  }
1296
1334
  };
1297
1335
  const decoratedRows = /* @__PURE__ */ new WeakMap();
1336
+ const failedRowState = (row) => {
1337
+ const state = row.getAttribute(TOOL_ROW_STATE_ATTRIBUTE);
1338
+ return state !== null && TOOL_ROW_FAILED_STATES.includes(state);
1339
+ };
1340
+ const promoteInterruptedDraft = (row, callId) => {
1341
+ if (timedOut.has(callId) || passive.has(callId)) return;
1342
+ const items = lastDrafts.get(callId);
1343
+ if (items === void 0 || !items.some(hasItemContent)) return;
1344
+ if (!drafts.has(callId)) {
1345
+ const container = row.closest(SESSION_CONTAINER_SELECTOR);
1346
+ const sessionId = container instanceof HTMLElement ? container.getAttribute("data-conversation-session") ?? void 0 : callSessionOf(callId);
1347
+ if (sessionId === void 0 || sessionId === "") return;
1348
+ drafts.set(callId, {
1349
+ sessionId,
1350
+ callId,
1351
+ questions: projectedQuestions.get(callId) ?? [],
1352
+ items
1353
+ });
1354
+ pruneDrafts();
1355
+ }
1356
+ interrupted.add(callId);
1357
+ };
1298
1358
  const decorateRow = (row) => {
1299
1359
  const callId = resolveCallId(row);
1300
1360
  if (callId === void 0) return;
1301
- const plain = !timedOut.has(callId) && !passive.has(callId) && !drafts.has(callId);
1302
- const signature = callId + (row.querySelector("button.dqtp-question-bubble") !== null ? "1" : "0") + (timedOut.has(callId) ? "T" : "-") + (passive.has(callId) ? "P" : "-");
1361
+ if (failedRowState(row)) promoteInterruptedDraft(row, callId);
1362
+ const plain = !timedOut.has(callId) && !passive.has(callId) && !interrupted.has(callId) && !drafts.has(callId);
1363
+ const signature = callId + (row.querySelector("button.dqtp-question-bubble") !== null ? "1" : "0") + (timedOut.has(callId) ? "T" : "-") + (passive.has(callId) ? "P" : "-") + (interrupted.has(callId) ? "I" : "-");
1303
1364
  if (plain && decoratedRows.get(row) === signature) return;
1304
- if (!timedOut.has(callId)) {
1365
+ if (!timedOut.has(callId) && !interrupted.has(callId)) {
1305
1366
  showHostReopen(row);
1306
1367
  showHostWaitText(row);
1307
1368
  }
@@ -1326,7 +1387,7 @@ function installQuestionTimeoutAdapter(ctx, source) {
1326
1387
  const label = pick(BUBBLE_DRAFT_LABEL_ZH, BUBBLE_DRAFT_LABEL_EN);
1327
1388
  if (button.textContent !== label) button.textContent = label;
1328
1389
  if (button.getAttribute("data-dqtp-bubble") !== "draft") button.setAttribute(BUBBLE_STATE_ATTRIBUTE, BUBBLE_STATE_DRAFT);
1329
- if (timedOut.has(callId)) {
1390
+ if (timedOut.has(callId) || interrupted.has(callId)) {
1330
1391
  hideHostReopen(row);
1331
1392
  hideHostWaitText(row);
1332
1393
  }
@@ -1361,7 +1422,7 @@ function installQuestionTimeoutAdapter(ctx, source) {
1361
1422
  draftTooLargeAt.delete(identity.callId);
1362
1423
  }
1363
1424
  if (timedOut.has(identity.callId) || passive.has(identity.callId)) return;
1364
- if (!callActive.has(identity.callId)) return;
1425
+ if (!callActive.has(identity.callId) && !hostStillWaiting(card)) return;
1365
1426
  rememberCallSession(identity);
1366
1427
  const progress = readProgress(card);
1367
1428
  const projected = projectedCounts.get(identity.callId) ?? 1;
@@ -1398,6 +1459,16 @@ function installQuestionTimeoutAdapter(ctx, source) {
1398
1459
  return;
1399
1460
  }
1400
1461
  if (settled) return;
1462
+ if (reply.reason === "bad-call-id") {
1463
+ if (!badCallIdWarned.has(callId)) {
1464
+ badCallIdWarned.add(callId);
1465
+ console.warn("[question-timeout-protection] 调用标识不符合通道格式, 这一轮的草稿无法送达");
1466
+ }
1467
+ syncUnavailable.add(callId);
1468
+ const badIdCard = findCard(identity);
1469
+ if (badIdCard !== void 0) decorateCard(badIdCard, identity);
1470
+ return;
1471
+ }
1401
1472
  if (reply.reason === "too-large") {
1402
1473
  draftTooLargeAt.set(identity.callId, Date.now());
1403
1474
  if (!draftTooLarge.has(identity.callId)) {
@@ -1429,8 +1500,9 @@ function installQuestionTimeoutAdapter(ctx, source) {
1429
1500
  }
1430
1501
  handled.add(row.callId);
1431
1502
  deferred.delete(row.callId);
1432
- const count = row.questions.length;
1433
- const liveIndex = card === void 0 ? void 0 : readProgress(card)?.index;
1503
+ const progress = card === void 0 ? void 0 : readProgress(card);
1504
+ const count = Math.max(progress?.count ?? 1, projectedCounts.get(row.callId) ?? 1, row.questions.length);
1505
+ const liveIndex = progress?.index;
1434
1506
  const items = mergeDrafts(gateDraftSelections(readHostDrafts(identity, count), identity.callId), readLiveDrafts(card, count, card === void 0 ? [] : readLiveSelected(card, row.callId)), stored, count, liveIndex);
1435
1507
  lastDrafts.set(row.callId, items);
1436
1508
  const current = options();
@@ -1464,7 +1536,13 @@ function installQuestionTimeoutAdapter(ctx, source) {
1464
1536
  const evaluateProjection = (sessionId, snapshot) => {
1465
1537
  if (typeof snapshot !== "object" || snapshot === null) return;
1466
1538
  const active = snapshot.active;
1467
- if (!Array.isArray(active)) return;
1539
+ if (!Array.isArray(active)) {
1540
+ if (!evaluateWarned.has(sessionId)) {
1541
+ evaluateWarned.add(sessionId);
1542
+ console.warn("[question-timeout-protection] 提问投影结构不符, 该会话的超时接管可能不会生效");
1543
+ }
1544
+ return;
1545
+ }
1468
1546
  const live = /* @__PURE__ */ new Set();
1469
1547
  for (const row of active) {
1470
1548
  if (typeof row.callId !== "string") continue;
@@ -1563,9 +1641,16 @@ function installQuestionTimeoutAdapter(ctx, source) {
1563
1641
  subscriptionSeen.delete(oldestSession);
1564
1642
  const evictedSession = oldestSession;
1565
1643
  polledSessions.set(evictedSession, () => {
1566
- const face = resolveProjectionFace(ctx, evictedSession);
1567
- if (face === void 0) return;
1568
- evaluateProjection(evictedSession, face.getSnapshot?.());
1644
+ try {
1645
+ const face = resolveProjectionFace(ctx, evictedSession);
1646
+ if (face === void 0) return;
1647
+ evaluateProjection(evictedSession, face.getSnapshot?.());
1648
+ } catch (error) {
1649
+ if (!evaluateWarned.has(evictedSession)) {
1650
+ evaluateWarned.add(evictedSession);
1651
+ console.warn("[question-timeout-protection] 评估提问投影时出错, 该会话的兜底可能受影响", error);
1652
+ }
1653
+ }
1569
1654
  });
1570
1655
  subscriptionSeen.set(evictedSession, Date.now());
1571
1656
  enforcePolledLimit();
@@ -1677,7 +1762,7 @@ function installQuestionTimeoutAdapter(ctx, source) {
1677
1762
  }
1678
1763
  subscriptionSeen.set(identity.sessionId, Date.now());
1679
1764
  ensureSubscription(identity.sessionId);
1680
- if (enhancementOn && callActive.has(identity.callId)) {
1765
+ if (enhancementOn && (callActive.has(identity.callId) || hostStillWaiting(element))) {
1681
1766
  const previous = lastDrafts.get(identity.callId);
1682
1767
  const progress = readProgress(element);
1683
1768
  const count = Math.max(progress?.count ?? 1, previous?.length ?? 1);
@@ -1719,6 +1804,11 @@ function installQuestionTimeoutAdapter(ctx, source) {
1719
1804
  };
1720
1805
  const onDraftStorageChange = (event) => {
1721
1806
  const key = event.key;
1807
+ if (key === "dsh.question-timeout-protection.auto-infinite") {
1808
+ autoInfinite = readAutoInfinite();
1809
+ scheduleScan();
1810
+ return;
1811
+ }
1722
1812
  if (typeof key === "string" && !key.startsWith("dsh.user-questions.drafts.v1")) return;
1723
1813
  invalidateHostDraftCache();
1724
1814
  scheduleScan();
@@ -1760,6 +1850,7 @@ function installQuestionTimeoutAdapter(ctx, source) {
1760
1850
  }
1761
1851
  for (const element of Array.from(document.querySelectorAll("[data-dqtp-countdown], button.dqtp-infinite-wait, button.dqtp-question-bubble"))) element.remove();
1762
1852
  for (const element of Array.from(document.querySelectorAll("." + HIDDEN_CONTROL_CLASS))) element.classList.remove(HIDDEN_CONTROL_CLASS);
1853
+ for (const element of Array.from(document.querySelectorAll("[data-dqtp-host-wait]"))) element.removeAttribute(HIDDEN_WAIT_ATTRIBUTE);
1763
1854
  for (const element of Array.from(document.querySelectorAll("button.dqtp-auto-infinite"))) element.remove();
1764
1855
  releaseStyle();
1765
1856
  enhancementUsers -= 1;
@@ -1779,7 +1870,7 @@ const ZH = {
1779
1870
  injectLabel: "注入到上下文",
1780
1871
  injectDesc: "超时前把草稿快照交给服务端, 到期时随工具结果按题带回模型上下文, 由模型自行决定是否重新提问",
1781
1872
  fixedSection: "固定特性",
1782
- fixedNote: "随插件启用状态生效, 不可单独关闭",
1873
+ fixedNote: "随插件启用状态生效, 本页不提供开关",
1783
1874
  fixedKeepLabel: "界面保留草稿",
1784
1875
  fixedKeepDesc: "超时后把已选选项与已输入内容记入提问气泡, 可在气泡里只读查看",
1785
1876
  cardEnhancementsLabel: "卡片增强",
@@ -1799,7 +1890,7 @@ const EN = {
1799
1890
  injectLabel: "Inject into context",
1800
1891
  injectDesc: "The draft snapshot is sent to the server before the timeout; on expiry it comes back with the tool result per question and enters the model context, so the model can decide whether to ask again",
1801
1892
  fixedSection: "Fixed features",
1802
- fixedNote: "Follows the plugin's enabled state and cannot be turned off separately",
1893
+ fixedNote: "Follows the plugin's enabled state; this page offers no switch",
1803
1894
  fixedKeepLabel: "Keep the draft in the UI",
1804
1895
  fixedKeepDesc: "At timeout, records the selected options and typed text into the question bubble, where they can be viewed read-only",
1805
1896
  cardEnhancementsLabel: "Card enhancements",
package/dist/index.mjs CHANGED
@@ -50,6 +50,25 @@ function injectsContext(mode) {
50
50
  const DRAFT_GRACE_MS = 3e3;
51
51
  /** 客户端状态同步端点路径 */
52
52
  const SYNC_PATH = "/question-timeout-protection/state";
53
+ /** 外层程序未显式声明预算时的兜底值(毫秒), 与宿主 run_code 的缺省预算一致 */
54
+ const DEFAULT_PTC_BUDGET_MS = 12e4;
55
+ /** 在外层预算到期前预留的收尾时间(毫秒): 覆盖最多两次取草稿的宽限期(DRAFT_GRACE_MS)与结算竞态 */
56
+ const PTC_BUDGET_MARGIN_MS = 7e3;
57
+ /**
58
+ * 外层预算不足以等待作答时的说明(模型侧)。
59
+ * 这一轮没有真正等待, 用户也没看到问题, 因此必须让模型知道重试时要放宽外层预算。
60
+ */
61
+ const TIMEOUT_PENDING_BUDGET_NOTICE = "外层 run_code 的剩余执行预算不足以等待用户作答, 这次提问没有开始等待, 用户也没有看到问题; 需要提问时请把 run_code 的 timeoutMs 设为大于提问等待时长后重试。";
62
+ /**
63
+ * 注入给模型的草稿文本上限(字符): 单题与整轮。
64
+ * 草稿随工具结果进入上下文, 宿主可能带工具结果裁剪(如 PTC 预设的 8192 字符阈值),
65
+ * 超长的草稿会被整段吃掉, 因此插件自己先按上限截断并说明。
66
+ */
67
+ const MAX_DRAFT_QUESTION_CHARS = 1200;
68
+ /** 整轮草稿的注入上限(字符) */
69
+ const MAX_DRAFT_TOTAL_CHARS = 6e3;
70
+ /** 草稿因上限被截断时的补充说明(模型侧) */
71
+ const TIMEOUT_PENDING_DRAFT_TRUNCATED_NOTICE = "草稿过长, 超过上限的部分已截断。";
53
72
  // src/config-value.ts
54
73
  /** 读取 volatile 字段的当前值, 兼容普通值 */
55
74
  function configValue(value) {
@@ -69,6 +88,154 @@ const Config = Schema.object({
69
88
  infiniteWait: Schema.boolean().default(true).volatile(),
70
89
  draftFallback: Schema.boolean().default(true).volatile()
71
90
  });
91
+ // src/ptc/budget.ts
92
+ const runBudgets = /* @__PURE__ */ new Map();
93
+ const nestedBudgets = /* @__PURE__ */ new Map();
94
+ const NESTED_BUDGET_GRACE_MS = 5e3;
95
+ /**
96
+ * 登记一次外层程序的到期时刻。
97
+ * 同一调用会先由调用事件、再由派发钩子登记一次, 取较晚的到期时刻:
98
+ * 派发发生在调用之后, 取较晚的才不会被前置包装低估预算。
99
+ */
100
+ function registerRunBudget(callId, deadline) {
101
+ const previous = runBudgets.get(callId);
102
+ if (previous !== void 0 && previous >= deadline) return;
103
+ runBudgets.delete(callId);
104
+ runBudgets.set(callId, deadline);
105
+ const now = Date.now();
106
+ for (const [id, value] of runBudgets) if (now - value > 18e5) runBudgets.delete(id);
107
+ while (runBudgets.size > 512) {
108
+ const oldest = runBudgets.keys().next();
109
+ if (oldest.done) break;
110
+ runBudgets.delete(oldest.value);
111
+ }
112
+ }
113
+ /** 登记一次内层程序的到期时刻(嵌套 run_code) */
114
+ function registerNestedBudget(rootCallId, callId, deadline) {
115
+ if (rootCallId === "") return;
116
+ let entries = nestedBudgets.get(rootCallId);
117
+ if (entries === void 0) {
118
+ entries = /* @__PURE__ */ new Map();
119
+ nestedBudgets.set(rootCallId, entries);
120
+ }
121
+ const previous = entries.get(callId);
122
+ if (previous !== void 0 && previous >= deadline) return;
123
+ entries.set(callId, deadline);
124
+ while (entries.size > 512) {
125
+ const oldest = entries.keys().next();
126
+ if (oldest.done) break;
127
+ entries.delete(oldest.value);
128
+ }
129
+ while (nestedBudgets.size > 512) {
130
+ const oldest = nestedBudgets.keys().next();
131
+ if (oldest.done) break;
132
+ nestedBudgets.delete(oldest.value);
133
+ }
134
+ }
135
+ /** 丢弃一次内层程序的登记(内层调用结算时) */
136
+ function clearNestedBudget(callId) {
137
+ for (const [rootCallId, entries] of nestedBudgets) {
138
+ if (!entries.delete(callId)) continue;
139
+ if (entries.size === 0) nestedBudgets.delete(rootCallId);
140
+ }
141
+ }
142
+ /** 丢弃一次外层程序的登记: 根结算时连它名下的内层登记一起清掉 */
143
+ function clearRunBudget(callId) {
144
+ runBudgets.delete(callId);
145
+ clearNestedBudget(callId);
146
+ nestedBudgets.delete(callId);
147
+ }
148
+ /**
149
+ * 读外层程序的剩余预算(毫秒)。
150
+ * 未登记返回 undefined: 不是 PTC 子调用, 或这次 run_code 的调用事件还没到。
151
+ * 已过期返回 0, 让调用方按"预算不足"处理而不是当成无限预算。
152
+ */
153
+ function runBudgetRemaining(callId) {
154
+ let deadline = runBudgets.get(callId);
155
+ const nested = nestedBudgets.get(callId);
156
+ if (nested !== void 0) {
157
+ const now = Date.now();
158
+ for (const [id, value] of nested) {
159
+ if (value + NESTED_BUDGET_GRACE_MS <= now) {
160
+ nested.delete(id);
161
+ continue;
162
+ }
163
+ if (deadline === void 0 || value < deadline) deadline = value;
164
+ }
165
+ if (nested.size === 0) nestedBudgets.delete(callId);
166
+ }
167
+ if (deadline === void 0) return void 0;
168
+ const remaining = deadline - Date.now();
169
+ return remaining > 0 ? remaining : 0;
170
+ }
171
+ /** 清空全部登记(插件卸载时) */
172
+ function resetRunBudgets() {
173
+ runBudgets.clear();
174
+ nestedBudgets.clear();
175
+ }
176
+ function readBudgetMs(value, fallback) {
177
+ let args = value;
178
+ if (typeof args === "string") try {
179
+ args = JSON.parse(args);
180
+ } catch {
181
+ return fallback;
182
+ }
183
+ if (args === null || typeof args !== "object") return fallback;
184
+ const requested = args.timeoutMs;
185
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return fallback;
186
+ return Math.round(requested);
187
+ }
188
+ /**
189
+ * 监听会话事件, 登记每次 run_code 的到期时刻。
190
+ * @param ctx 插件上下文, 只在根上注册一次
191
+ * @param defaultBudgetMs 外层未声明预算时的兜底值, 延迟读取以兼容 PTC 服务后到
192
+ * @returns 注销函数
193
+ */
194
+ function installRunBudgetTracking(ctx, defaultBudgetMs) {
195
+ const source = ctx;
196
+ const executeSource = ctx;
197
+ let off;
198
+ let offExecute;
199
+ try {
200
+ offExecute = executeSource.on("tools/execute", async (exec, next) => {
201
+ try {
202
+ if (exec !== null && typeof exec === "object" && exec.name === "run_code" && typeof exec.callId === "string" && exec.callId !== "") {
203
+ const deadline = Date.now() + readBudgetMs(exec.arguments, defaultBudgetMs());
204
+ if (exec.parent === void 0) registerRunBudget(exec.callId, deadline);
205
+ else registerNestedBudget(typeof exec.rootCallId === "string" ? exec.rootCallId : "", exec.callId, deadline);
206
+ }
207
+ } catch {}
208
+ return next();
209
+ });
210
+ } catch (error) {
211
+ console.warn("[question-timeout-protection] 无法挂上工具派发钩子, PTC 外层预算起点退化为调用时刻", String(error));
212
+ }
213
+ try {
214
+ off = source.on("session/event", (_session, event) => {
215
+ if (event === null || typeof event !== "object") return;
216
+ const type = event.type;
217
+ if (type !== "tool/call" && type !== "tool/result") return;
218
+ const data = event.data;
219
+ if (data === null || data === void 0 || typeof data !== "object") return;
220
+ if (type === "tool/result") {
221
+ const settledId = data.message?.toolCallId;
222
+ if (typeof settledId === "string" && settledId !== "") clearRunBudget(settledId);
223
+ return;
224
+ }
225
+ const callId = data.callId;
226
+ if (typeof callId !== "string" || callId === "") return;
227
+ if (data.name !== "run_code") return;
228
+ registerRunBudget(callId, (typeof event.time === "number" ? event.time : Date.now()) + readBudgetMs(data.arguments, defaultBudgetMs()));
229
+ });
230
+ } catch (error) {
231
+ console.warn("[question-timeout-protection] 无法监听会话事件, PTC 外层预算感知未生效", String(error));
232
+ }
233
+ return () => {
234
+ offExecute?.();
235
+ off?.();
236
+ resetRunBudgets();
237
+ };
238
+ }
72
239
  // src/sync/server.ts
73
240
  const infiniteCalls = /* @__PURE__ */ new Map();
74
241
  const MAX_BODY_LENGTH = 262144;
@@ -136,6 +303,7 @@ function markCallSettled(callId) {
136
303
  if (oldest.done) break;
137
304
  settledCalls.delete(oldest.value);
138
305
  }
306
+ sweepTrackedCalls();
139
307
  }
140
308
  function sleep(ms) {
141
309
  return new Promise((resolve) => {
@@ -310,7 +478,6 @@ function handleStateRequest(request, response) {
310
478
  reason: "too-large"
311
479
  }));
312
480
  chunks.length = 0;
313
- request.destroy();
314
481
  }
315
482
  });
316
483
  request.on("error", (error) => {
@@ -327,8 +494,11 @@ function handleStateRequest(request, response) {
327
494
  try {
328
495
  const parsed = JSON.parse(body);
329
496
  if (typeof parsed.callId !== "string" || !CALL_ID_PATTERN.test(parsed.callId)) {
330
- response.writeHead(400);
331
- response.end();
497
+ response.writeHead(400, { "content-type": "application/json" });
498
+ response.end(JSON.stringify({
499
+ ok: false,
500
+ reason: "bad-call-id"
501
+ }));
332
502
  return;
333
503
  }
334
504
  if (parsed.infinite === false) clearInfiniteWait(parsed.callId);
@@ -473,7 +643,7 @@ function stopQuestionSync() {
473
643
  clearSyncState();
474
644
  }
475
645
  // src/question/tool.ts
476
- const TOOL_DESCRIPTION = "Ask brief, direct, self-contained questions about missing information, preferences, or decisions. Use user-facing terms; assume no knowledge of background work or internal names. Use distinct stable question IDs. A timed call that expires before an answer batch returns a pending result: that round has already been settled as timed out, and an answer submitted later is not adopted by this tool, so decide yourself whether to ask again.";
646
+ const TOOL_DESCRIPTION = "Ask brief, direct, self-contained questions about missing information, preferences, or decisions. Use user-facing terms; assume no knowledge of background work or internal names. Use distinct stable question IDs. A timed call that expires before an answer batch returns a pending result: that round has already been settled as timed out, and an answer submitted later is not adopted by this tool, so decide yourself whether to ask again. A timed call made from inside run_code is additionally bounded by that program's elapsed-time budget: keep the enclosing run_code timeoutMs above this timeout, otherwise the question is aborted and no draft can be returned.";
477
647
  const QUESTIONS_DESCRIPTION = "Questions to ask the user.";
478
648
  function resolveTimeout(requested, fallback) {
479
649
  const raw = requested ?? fallback;
@@ -603,7 +773,7 @@ function createAskUserQuestionTool(ctx, config) {
603
773
  },
604
774
  [TIMED_TIMEOUT_PARAMETER]: {
605
775
  type: "integer",
606
- description: `Wait seconds for the entire question batch (default ${String(configValue(config.timeoutSeconds) ?? 120)}). Pass -1 only when an answer is required before proceeding.`
776
+ description: `Wait seconds for the entire question batch (default ${String(configValue(config.timeoutSeconds) ?? 120)}). Pass -1 only when an answer is required before proceeding. Inside run_code, set the enclosing run_code timeoutMs above this value.`
607
777
  }
608
778
  },
609
779
  output: {
@@ -737,7 +907,16 @@ function createAskUserQuestionTool(ctx, config) {
737
907
  markCallSettled(exec.callId);
738
908
  }
739
909
  if (exec.agent === void 0) throw new Error("timed questions require a live agent");
740
- const timeoutMs = timeoutSeconds * 1e3;
910
+ const requestedTimeoutMs = timeoutSeconds * 1e3;
911
+ const parentCallId = exec.rootCallId === exec.callId ? void 0 : exec.rootCallId;
912
+ const parentRemaining = parentCallId === void 0 ? void 0 : runBudgetRemaining(parentCallId);
913
+ const usableMs = parentRemaining === void 0 ? void 0 : parentRemaining - PTC_BUDGET_MARGIN_MS;
914
+ if (usableMs !== void 0 && usableMs < 2e3) return {
915
+ pending: true,
916
+ callId: exec.callId,
917
+ message: TIMEOUT_PENDING_BUDGET_NOTICE
918
+ };
919
+ const timeoutMs = usableMs === void 0 ? requestedTimeoutMs : Math.min(requestedTimeoutMs, usableMs);
741
920
  registerCallDeadline(exec.callId, Date.now() + timeoutMs);
742
921
  registerCallQuestions(exec.callId, questions.map((question) => question.id));
743
922
  const waitController = new AbortController();
@@ -813,6 +992,8 @@ function createAskUserQuestionTool(ctx, config) {
813
992
  if (authority !== void 0 && draft.some((item) => item.index >= authority.length)) console.warn("[question-timeout-protection] 草稿的题目序号超出本次提问的题目数, 多余的部分已丢弃");
814
993
  const mapped = [];
815
994
  let dropped = 0;
995
+ let remainingChars = MAX_DRAFT_TOTAL_CHARS;
996
+ let truncated = false;
816
997
  for (const item of draft) {
817
998
  const question = questions[item.index];
818
999
  if (question === void 0) {
@@ -821,10 +1002,25 @@ function createAskUserQuestionTool(ctx, config) {
821
1002
  }
822
1003
  const custom = item.custom?.trim() ?? "";
823
1004
  if (item.selected.length === 0 && custom === "") continue;
1005
+ const selected = [...item.selected];
1006
+ const questionLimit = Math.min(MAX_DRAFT_QUESTION_CHARS, remainingChars);
1007
+ const selectedChars = selected.reduce((sum, label) => sum + label.length, 0);
1008
+ if (selectedChars > questionLimit) {
1009
+ truncated = true;
1010
+ break;
1011
+ }
1012
+ const room = questionLimit - selectedChars;
1013
+ const keptCustom = custom.length > room ? custom.slice(0, room) : custom;
1014
+ if (keptCustom.length !== custom.length) truncated = true;
1015
+ if (selected.length === 0 && keptCustom === "") {
1016
+ truncated = true;
1017
+ break;
1018
+ }
1019
+ remainingChars -= selectedChars + keptCustom.length;
824
1020
  mapped.push({
825
1021
  id: question.id,
826
- selected: [...item.selected],
827
- ...custom === "" ? {} : { custom }
1022
+ selected,
1023
+ ...keptCustom === "" ? {} : { custom: keptCustom }
828
1024
  });
829
1025
  }
830
1026
  if (dropped > 0) console.warn("[question-timeout-protection] 有 " + String(dropped) + " 条草稿对不上本次提问的题目, 已丢弃");
@@ -836,7 +1032,7 @@ function createAskUserQuestionTool(ctx, config) {
836
1032
  return {
837
1033
  pending: true,
838
1034
  callId,
839
- message: TIMEOUT_PENDING_DRAFT_NOTICE,
1035
+ message: truncated ? TIMEOUT_PENDING_DRAFT_NOTICE + TIMEOUT_PENDING_DRAFT_TRUNCATED_NOTICE : TIMEOUT_PENDING_DRAFT_NOTICE,
840
1036
  draft: mapped
841
1037
  };
842
1038
  }
@@ -1068,6 +1264,12 @@ const inject = [
1068
1264
  function apply(ctx, config) {
1069
1265
  const service = new QuestionTimeoutService(ctx, config);
1070
1266
  service.start();
1267
+ let ptcDefaultBudgetMs = DEFAULT_PTC_BUDGET_MS;
1268
+ ctx.inject(["ptcRuntime"], (scoped) => {
1269
+ const value = (scoped ?? ctx).ptcRuntime?.timeout?.defaultMs;
1270
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) ptcDefaultBudgetMs = value;
1271
+ });
1272
+ ctx.effect(() => installRunBudgetTracking(ctx, () => ptcDefaultBudgetMs));
1071
1273
  let syncStarted = false;
1072
1274
  ctx.inject(["webServer"], (scoped) => {
1073
1275
  const holder = scoped ?? ctx;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-question-timeout-protection",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "dsh提问超时保护插件: 一旦模型提问超时,将你的回答草稿保留在UI或上下文中,而不是直接丢弃。",
5
5
  "type": "module",
6
6
  "author": "JularDepick",
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "engines": {
13
13
  "node": ">=20",
14
- "dsh": ">=0.2.1-rc.1 <=0.2.2-rc.2"
14
+ "dsh": ">=0.2.1-rc.1 <0.2.3-rc.1"
15
15
  },
16
16
  "main": "./dist/index.mjs",
17
17
  "types": "./dist/index.d.mts",
@@ -51,23 +51,23 @@
51
51
  },
52
52
  "peerDependencies": {
53
53
  "@deepseek-ai/cordis": "~4.0.5 || ~4.1.0",
54
- "@deepseek-ai/dsh-agent": ">=0.2.1-rc.1 <=0.2.2-rc.2",
55
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.1 <=0.2.2-rc.2",
56
- "@deepseek-ai/dsh-user-questions": ">=0.2.1-rc.1 <=0.2.2-rc.2"
54
+ "@deepseek-ai/dsh-agent": ">=0.2.1-rc.1 <0.2.3-rc.1",
55
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.1 <0.2.3-rc.1",
56
+ "@deepseek-ai/dsh-user-questions": ">=0.2.1-rc.1 <0.2.3-rc.1"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@deepseek-ai/cordis": "~4.1.0",
60
- "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
61
- "@deepseek-ai/dsh-client-locale": "0.2.2-rc.2",
62
- "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.2",
63
- "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.2",
64
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.2",
65
- "@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.2",
66
- "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.2",
67
- "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
68
- "@deepseek-ai/dsh-session": "0.2.2-rc.2",
69
- "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
70
- "@deepseek-ai/dsh-user-questions": "0.2.2-rc.2",
60
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.3",
61
+ "@deepseek-ai/dsh-client-locale": "0.2.2-rc.3",
62
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.3",
63
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.3",
64
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.3",
65
+ "@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.3",
66
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.3",
67
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.3",
68
+ "@deepseek-ai/dsh-session": "0.2.2-rc.3",
69
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.3",
70
+ "@deepseek-ai/dsh-user-questions": "0.2.2-rc.3",
71
71
  "@types/node": "^26.2.0",
72
72
  "@types/react": "^18.3.31",
73
73
  "react": "^18.2.0",
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.2
2
+ for=v0.1.4
3
3
  lang=zh-CN
4
4
  name=简体中文
5
- endtime=2026-11-12 18:50:00+08:00
5
+ endtime=2026-11-15 14:20:00+08:00
6
6
 
7
7
  [translation]
8
8
  settings.settingsSummary=提问超时保护
@@ -11,7 +11,7 @@ settings.fallbackNote=提问超时后如何处理已经输入的内容
11
11
  settings.injectLabel=注入到上下文
12
12
  settings.injectDesc=超时前把草稿快照交给服务端, 到期时随工具结果按题带回模型上下文, 由模型自行决定是否重新提问
13
13
  settings.fixedSection=固定特性
14
- settings.fixedNote=随插件启用状态生效, 不可单独关闭
14
+ settings.fixedNote=随插件启用状态生效, 本页不提供开关
15
15
  settings.fixedKeepLabel=界面保留草稿
16
16
  settings.fixedKeepDesc=超时后把已选选项与已输入内容记入提问气泡, 可在气泡里只读查看
17
17
  settings.cardEnhancementsLabel=卡片增强
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.2
2
+ for=v0.1.4
3
3
  lang=en-US
4
4
  name=English (US)
5
- endtime=2026-11-12 19:20:00+08:00
5
+ endtime=2026-11-15 14:20:00+08:00
6
6
 
7
7
  [translation]
8
8
  settings.settingsSummary=Question timeout protection
@@ -11,7 +11,7 @@ settings.fallbackNote=What happens to the content the user already typed once th
11
11
  settings.injectLabel=Inject into context
12
12
  settings.injectDesc=The draft snapshot is sent to the server before the timeout; on expiry it comes back with the tool result per question and enters the model context, so the model can decide whether to ask again
13
13
  settings.fixedSection=Fixed features
14
- settings.fixedNote=Follows the plugin's enabled state and cannot be turned off separately
14
+ settings.fixedNote=Follows the plugin's enabled state; this page offers no switch
15
15
  settings.fixedKeepLabel=Keep the draft in the UI
16
16
  settings.fixedKeepDesc=At timeout, records the selected options and typed text into the question bubble, where they can be viewed read-only
17
17
  settings.cardEnhancementsLabel=Card enhancements
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.2
2
+ for=v0.1.4
3
3
  lang=zh-CN
4
4
  name=简体中文
5
- endtime=2026-11-12 18:50:00+08:00
5
+ endtime=2026-11-15 14:20:00+08:00
6
6
 
7
7
  [translation]
8
8
  settings.settingsSummary=提问超时保护
@@ -11,7 +11,7 @@ settings.fallbackNote=提问超时后如何处理已经输入的内容
11
11
  settings.injectLabel=注入到上下文
12
12
  settings.injectDesc=超时前把草稿快照交给服务端, 到期时随工具结果按题带回模型上下文, 由模型自行决定是否重新提问
13
13
  settings.fixedSection=固定特性
14
- settings.fixedNote=随插件启用状态生效, 不可单独关闭
14
+ settings.fixedNote=随插件启用状态生效, 本页不提供开关
15
15
  settings.fixedKeepLabel=界面保留草稿
16
16
  settings.fixedKeepDesc=超时后把已选选项与已输入内容记入提问气泡, 可在气泡里只读查看
17
17
  settings.cardEnhancementsLabel=卡片增强