dsh-question-timeout-protection 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -30,18 +30,18 @@ const TIMED_TIMEOUT_PARAMETER = "timeout";
30
30
  * 语义要点: 只说明本轮提问已超时、用户没有正式提交, 不对草稿做任何断言 ——
31
31
  * 草稿为空时不该告诉模型"草稿保留了下来"; 有草稿时草稿走 draft 字段随本结果一起回来。
32
32
  */
33
- const TIMEOUT_PENDING_NOTICE = "该轮提问已超时,用户没有正式提交; 请在回复末尾告知用户这一点。";
33
+ const TIMEOUT_PENDING_NOTICE = "该轮提问已超时,用户没有正式提交; 界面可能已经收起这张卡片, 也可能仍可作答 —— 用户之后补交的答复会作为一条用户消息送达, 请勿把超时本身或草稿当成用户的确认; 请在回复末尾告知用户这一点。";
34
34
  /**
35
35
  * 没有收到任何草稿快照时的说明。
36
36
  * 与「收到空草稿」不同: 后者表示用户确实没写, 前者是快照没送达, 模型不能据此断定用户没输入。
37
37
  */
38
- const TIMEOUT_PENDING_MISSING_NOTICE = "该轮提问已超时,用户没有正式提交; 本轮没有收到草稿快照(草稿通道不可达或页面未打开), 因此拿不到超时前的输入内容, 请不要据此断言用户没有输入, 并在回复末尾告知用户这次提问已超时。";
38
+ const TIMEOUT_PENDING_MISSING_NOTICE = "该轮提问已超时,用户没有正式提交; 本轮没有收到草稿快照(草稿通道不可达或页面未打开), 因此拿不到超时前的输入内容, 请不要据此断言用户没有输入; 界面可能已经收起这张卡片, 也可能仍可作答 —— 用户之后补交的答复会作为一条用户消息送达, 请勿把超时当成用户的确认; 并在回复末尾告知用户这次提问已超时。";
39
39
  /**
40
40
  * 有草稿时随 pending 结果返回给模型的说明。
41
41
  * 草稿本身放在 pending 结果的 draft 字段里, 这里只说明它的存在与用法,
42
42
  * 避免模型把整段说明当成草稿内容。
43
43
  */
44
- const TIMEOUT_PENDING_DRAFT_NOTICE = "该轮提问已超时,用户没有正式提交; 超时前留下的草稿已随本结果带回, 内容见 draft 字段, 请据此继续任务, 并在最后告知用户这次超时以及你对草稿的处理决策。";
44
+ const TIMEOUT_PENDING_DRAFT_NOTICE = "该轮提问已超时。用户未正式提交,但留下了一份草稿,详见 draft 字段。请自行判断草稿完整度、决定下一步事项。判断过程不得告知用户,在下一步事项之后总结报告对本次问答的决策结果。";
45
45
  /** 是否把超时草稿注入对话上下文 */
46
46
  function injectsContext(mode) {
47
47
  return mode === "context" || mode === "both";
@@ -50,6 +50,27 @@ 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 = 8e3;
57
+ /**
58
+ * 外层预算不足以等待作答时的说明(模型侧)。
59
+ * 这一轮没有真正等待, 用户也没看到问题, 因此必须让模型知道重试时要放宽外层预算。
60
+ * 该说明随工具错误返回, 不随 pending 结果: pending 会让宿主投影把调用转成可作答,
61
+ * 与"没有开始等待"矛盾。
62
+ */
63
+ const TIMEOUT_PENDING_BUDGET_NOTICE = "外层 run_code 的剩余执行预算不足以等待用户作答, 这次提问没有开始等待, 用户也没有看到问题; 需要提问时请把 run_code 的 timeoutMs 设为大于提问等待时长后重试。";
64
+ /**
65
+ * 注入给模型的草稿文本上限(字符): 单题与整轮。
66
+ * 草稿随工具结果进入上下文, 宿主可能带工具结果裁剪(如 PTC 预设的 8192 字符阈值),
67
+ * 超长的草稿会被整段吃掉, 因此插件自己先按上限截断并说明。
68
+ */
69
+ const MAX_DRAFT_QUESTION_CHARS = 1200;
70
+ /** 整轮草稿的注入上限(字符) */
71
+ const MAX_DRAFT_TOTAL_CHARS = 6e3;
72
+ /** 草稿因上限被截断时的补充说明(模型侧) */
73
+ const TIMEOUT_PENDING_DRAFT_TRUNCATED_NOTICE = "草稿过长, 超过上限的部分已截断。";
53
74
  // src/config-value.ts
54
75
  /** 读取 volatile 字段的当前值, 兼容普通值 */
55
76
  function configValue(value) {
@@ -69,6 +90,154 @@ const Config = Schema.object({
69
90
  infiniteWait: Schema.boolean().default(true).volatile(),
70
91
  draftFallback: Schema.boolean().default(true).volatile()
71
92
  });
93
+ // src/ptc/budget.ts
94
+ const runBudgets = /* @__PURE__ */ new Map();
95
+ const nestedBudgets = /* @__PURE__ */ new Map();
96
+ const NESTED_BUDGET_GRACE_MS = 5e3;
97
+ /**
98
+ * 登记一次外层程序的到期时刻。
99
+ * 同一调用会先由调用事件、再由派发钩子登记一次, 取较晚的到期时刻:
100
+ * 派发发生在调用之后, 取较晚的才不会被前置包装低估预算。
101
+ */
102
+ function registerRunBudget(callId, deadline) {
103
+ const previous = runBudgets.get(callId);
104
+ if (previous !== void 0 && previous >= deadline) return;
105
+ runBudgets.delete(callId);
106
+ runBudgets.set(callId, deadline);
107
+ const now = Date.now();
108
+ for (const [id, value] of runBudgets) if (now - value > 18e5) runBudgets.delete(id);
109
+ while (runBudgets.size > 512) {
110
+ const oldest = runBudgets.keys().next();
111
+ if (oldest.done) break;
112
+ runBudgets.delete(oldest.value);
113
+ }
114
+ }
115
+ /** 登记一次内层程序的到期时刻(嵌套 run_code) */
116
+ function registerNestedBudget(rootCallId, callId, deadline) {
117
+ if (rootCallId === "") return;
118
+ let entries = nestedBudgets.get(rootCallId);
119
+ if (entries === void 0) {
120
+ entries = /* @__PURE__ */ new Map();
121
+ nestedBudgets.set(rootCallId, entries);
122
+ }
123
+ const previous = entries.get(callId);
124
+ if (previous !== void 0 && previous >= deadline) return;
125
+ entries.set(callId, deadline);
126
+ while (entries.size > 512) {
127
+ const oldest = entries.keys().next();
128
+ if (oldest.done) break;
129
+ entries.delete(oldest.value);
130
+ }
131
+ while (nestedBudgets.size > 512) {
132
+ const oldest = nestedBudgets.keys().next();
133
+ if (oldest.done) break;
134
+ nestedBudgets.delete(oldest.value);
135
+ }
136
+ }
137
+ /** 丢弃一次内层程序的登记(内层调用结算时) */
138
+ function clearNestedBudget(callId) {
139
+ for (const [rootCallId, entries] of nestedBudgets) {
140
+ if (!entries.delete(callId)) continue;
141
+ if (entries.size === 0) nestedBudgets.delete(rootCallId);
142
+ }
143
+ }
144
+ /** 丢弃一次外层程序的登记: 根结算时连它名下的内层登记一起清掉 */
145
+ function clearRunBudget(callId) {
146
+ runBudgets.delete(callId);
147
+ clearNestedBudget(callId);
148
+ nestedBudgets.delete(callId);
149
+ }
150
+ /**
151
+ * 读外层程序的剩余预算(毫秒)。
152
+ * 未登记返回 undefined: 不是 PTC 子调用, 或这次 run_code 的调用事件还没到。
153
+ * 已过期返回 0, 让调用方按"预算不足"处理而不是当成无限预算。
154
+ */
155
+ function runBudgetRemaining(callId) {
156
+ let deadline = runBudgets.get(callId);
157
+ const nested = nestedBudgets.get(callId);
158
+ if (nested !== void 0) {
159
+ const now = Date.now();
160
+ for (const [id, value] of nested) {
161
+ if (value + NESTED_BUDGET_GRACE_MS <= now) {
162
+ nested.delete(id);
163
+ continue;
164
+ }
165
+ if (deadline === void 0 || value < deadline) deadline = value;
166
+ }
167
+ if (nested.size === 0) nestedBudgets.delete(callId);
168
+ }
169
+ if (deadline === void 0) return void 0;
170
+ const remaining = deadline - Date.now();
171
+ return remaining > 0 ? remaining : 0;
172
+ }
173
+ /** 清空全部登记(插件卸载时) */
174
+ function resetRunBudgets() {
175
+ runBudgets.clear();
176
+ nestedBudgets.clear();
177
+ }
178
+ function readBudgetMs(value, fallback) {
179
+ let args = value;
180
+ if (typeof args === "string") try {
181
+ args = JSON.parse(args);
182
+ } catch {
183
+ return fallback;
184
+ }
185
+ if (args === null || typeof args !== "object") return fallback;
186
+ const requested = args.timeoutMs;
187
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return fallback;
188
+ return Math.round(requested);
189
+ }
190
+ /**
191
+ * 监听会话事件, 登记每次 run_code 的到期时刻。
192
+ * @param ctx 插件上下文, 只在根上注册一次
193
+ * @param defaultBudgetMs 外层未声明预算时的兜底值, 延迟读取以兼容 PTC 服务后到
194
+ * @returns 注销函数
195
+ */
196
+ function installRunBudgetTracking(ctx, defaultBudgetMs) {
197
+ const source = ctx;
198
+ const executeSource = ctx;
199
+ let off;
200
+ let offExecute;
201
+ try {
202
+ offExecute = executeSource.on("tools/execute", async (exec, next) => {
203
+ try {
204
+ if (exec !== null && typeof exec === "object" && exec.name === "run_code" && typeof exec.callId === "string" && exec.callId !== "") {
205
+ const deadline = Date.now() + readBudgetMs(exec.arguments, defaultBudgetMs());
206
+ if (exec.parent === void 0) registerRunBudget(exec.callId, deadline);
207
+ else registerNestedBudget(typeof exec.rootCallId === "string" ? exec.rootCallId : "", exec.callId, deadline);
208
+ }
209
+ } catch {}
210
+ return next();
211
+ });
212
+ } catch (error) {
213
+ console.warn("[question-timeout-protection] 无法挂上工具派发钩子, PTC 外层预算起点退化为调用时刻", String(error));
214
+ }
215
+ try {
216
+ off = source.on("session/event", (_session, event) => {
217
+ if (event === null || typeof event !== "object") return;
218
+ const type = event.type;
219
+ if (type !== "tool/call" && type !== "tool/result") return;
220
+ const data = event.data;
221
+ if (data === null || data === void 0 || typeof data !== "object") return;
222
+ if (type === "tool/result") {
223
+ const settledId = data.message?.toolCallId;
224
+ if (typeof settledId === "string" && settledId !== "") clearRunBudget(settledId);
225
+ return;
226
+ }
227
+ const callId = data.callId;
228
+ if (typeof callId !== "string" || callId === "") return;
229
+ if (data.name !== "run_code") return;
230
+ registerRunBudget(callId, (typeof event.time === "number" ? event.time : Date.now()) + readBudgetMs(data.arguments, defaultBudgetMs()));
231
+ });
232
+ } catch (error) {
233
+ console.warn("[question-timeout-protection] 无法监听会话事件, PTC 外层预算感知未生效", String(error));
234
+ }
235
+ return () => {
236
+ offExecute?.();
237
+ off?.();
238
+ resetRunBudgets();
239
+ };
240
+ }
72
241
  // src/sync/server.ts
73
242
  const infiniteCalls = /* @__PURE__ */ new Map();
74
243
  const MAX_BODY_LENGTH = 262144;
@@ -85,7 +254,7 @@ let truncationWarned = false;
85
254
  const MAX_DRAFT_SNAPSHOTS = 256;
86
255
  const MAX_TRACKED_CALLS = 512;
87
256
  const TRACKED_CALL_TTL_MS = 9e5;
88
- const SETTLE_MS = 600;
257
+ const SETTLE_MS = 1e3;
89
258
  const POLL_INTERVAL_MS = 100;
90
259
  function rememberInfiniteCall(callId) {
91
260
  if (infiniteCalls.size >= MAX_INFINITE_CALLS && !infiniteCalls.has(callId)) {
@@ -174,7 +343,10 @@ function sweepTrackedCalls() {
174
343
  draftReports.delete(callId);
175
344
  }
176
345
  for (const callId of callQuestionOrders.keys()) if (!callDeadlines.has(callId)) callQuestionOrders.delete(callId);
177
- for (const [callId, registeredAt] of infiniteCalls) if (now - registeredAt > TRACKED_CALL_TTL_MS) infiniteCalls.delete(callId);
346
+ for (const [callId, registeredAt] of infiniteCalls) {
347
+ if (callDeadlines.has(callId)) continue;
348
+ if (now - registeredAt > TRACKED_CALL_TTL_MS) infiniteCalls.delete(callId);
349
+ }
178
350
  while (callDeadlines.size > MAX_TRACKED_CALLS) {
179
351
  const oldest = callDeadlines.keys().next();
180
352
  if (oldest.done) break;
@@ -216,20 +388,29 @@ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
216
388
  "localhost",
217
389
  "[::1]"
218
390
  ]);
219
- function isLoopbackHost(host) {
391
+ let allowedAuthority;
392
+ function authorityOf(origin) {
393
+ try {
394
+ return new URL(origin).host.toLowerCase();
395
+ } catch {
396
+ return;
397
+ }
398
+ }
399
+ function isTrustedHost(host) {
220
400
  if (host === void 0 || host === "") return false;
221
401
  try {
222
402
  const parsed = new URL("http://" + host);
223
403
  if (parsed.username !== "" || parsed.password !== "") return false;
224
404
  if (parsed.pathname !== "/" || parsed.search !== "" || parsed.hash !== "") return false;
225
- return LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase());
405
+ if (LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return true;
406
+ return allowedAuthority !== void 0 && parsed.host.toLowerCase() === allowedAuthority;
226
407
  } catch {
227
408
  return false;
228
409
  }
229
410
  }
230
411
  function serveToken(request, response) {
231
412
  if (request.method !== "GET" || request.url !== "/question-timeout-protection/state-token") return false;
232
- if (!isLoopbackHost(request.headers.host)) {
413
+ if (!isTrustedHost(request.headers.host)) {
233
414
  response.writeHead(403);
234
415
  response.end();
235
416
  return true;
@@ -252,7 +433,7 @@ function serveToken(request, response) {
252
433
  return true;
253
434
  }
254
435
  function handleStateRequest(request, response) {
255
- if (!isLoopbackHost(request.headers.host)) {
436
+ if (!isTrustedHost(request.headers.host)) {
256
437
  response.writeHead(403);
257
438
  response.end();
258
439
  return;
@@ -327,8 +508,11 @@ function handleStateRequest(request, response) {
327
508
  try {
328
509
  const parsed = JSON.parse(body);
329
510
  if (typeof parsed.callId !== "string" || !CALL_ID_PATTERN.test(parsed.callId)) {
330
- response.writeHead(400);
331
- response.end();
511
+ response.writeHead(400, { "content-type": "application/json" });
512
+ response.end(JSON.stringify({
513
+ ok: false,
514
+ reason: "bad-call-id"
515
+ }));
332
516
  return;
333
517
  }
334
518
  if (parsed.infinite === false) clearInfiniteWait(parsed.callId);
@@ -411,6 +595,10 @@ function registerQuestionSyncRoute(webServer) {
411
595
  off();
412
596
  } catch {}
413
597
  };
598
+ try {
599
+ const origin = webServer.getOrigin?.();
600
+ if (typeof origin === "string" && origin !== "") allowedAuthority = authorityOf(origin);
601
+ } catch {}
414
602
  syncChannelReady = true;
415
603
  console.info("[question-timeout-protection] 状态同步路由已挂在宿主 HTTP 服务上: " + SYNC_PATH);
416
604
  }
@@ -423,18 +611,9 @@ function registerQuestionSyncRoute(webServer) {
423
611
  if (channelUsers > 0) return;
424
612
  detachRoutes?.();
425
613
  detachRoutes = void 0;
426
- clearSyncState();
614
+ syncChannelReady = false;
427
615
  };
428
616
  }
429
- function clearSyncState() {
430
- syncChannelReady = false;
431
- infiniteCalls.clear();
432
- draftReports.clear();
433
- draftReportedAt.clear();
434
- callDeadlines.clear();
435
- callQuestionOrders.clear();
436
- settledCalls.clear();
437
- }
438
617
  let syncChannelReady = false;
439
618
  let channelUsers = 0;
440
619
  let detachRoutes;
@@ -467,14 +646,23 @@ function isInfiniteWait(callId) {
467
646
  function clearInfiniteWait(callId) {
468
647
  infiniteCalls.delete(callId);
469
648
  }
470
- /** 清空状态通道里登记的全部状态 */
649
+ /** 卸载状态通道: 只摘路由与就绪标志, 登记表留给 TTL 与容量上限回收 */
471
650
  function stopQuestionSync() {
472
651
  if (channelUsers > 0) return;
473
- clearSyncState();
652
+ detachRoutes?.();
653
+ detachRoutes = void 0;
654
+ syncChannelReady = false;
474
655
  }
475
656
  // 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.";
657
+ 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. Pass timeout as a top-level argument of this call, never inside a question item. An answer item with empty selected and no custom means the user skipped that question: continue without it, do not ask it again, and do not treat the skip as permission. A timed call that expires before an answer batch returns a pending result: that round timed out, the card may be closed or still answerable, and an answer the user submits later arrives as a separate user message, so never treat the pending result or its draft as a confirmed answer. 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 rejected without being shown and no draft can be returned.";
477
658
  const QUESTIONS_DESCRIPTION = "Questions to ask the user.";
659
+ function nestedTimeout(questions) {
660
+ for (const item of questions) {
661
+ if (item === null || typeof item !== "object") continue;
662
+ const value = item.timeout;
663
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 2147483) return value;
664
+ }
665
+ }
478
666
  function resolveTimeout(requested, fallback) {
479
667
  const raw = requested ?? fallback;
480
668
  if (raw === -1) return -1;
@@ -603,7 +791,7 @@ function createAskUserQuestionTool(ctx, config) {
603
791
  },
604
792
  [TIMED_TIMEOUT_PARAMETER]: {
605
793
  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.`
794
+ 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
795
  }
608
796
  },
609
797
  output: {
@@ -625,7 +813,7 @@ function createAskUserQuestionTool(ctx, config) {
625
813
  message: {
626
814
  type: "string",
627
815
  required: true,
628
- description: "How to continue while the questions stay answerable."
816
+ description: "How to continue after the timeout; the card may be closed or still answerable."
629
817
  },
630
818
  draftMissing: {
631
819
  type: "boolean",
@@ -634,7 +822,7 @@ function createAskUserQuestionTool(ctx, config) {
634
822
  },
635
823
  draft: {
636
824
  type: "array",
637
- description: "Unsubmitted draft the user had entered when the wait expired; one item per question, empty when there was no draft.",
825
+ description: "Unsubmitted draft the user had entered when the wait expired. It contains only questions that had a selection or typed text; a question missing from this list was not answered before the timeout, which is not the same as the user skipping it.",
638
826
  items: {
639
827
  type: "object",
640
828
  additionalProperties: false,
@@ -648,7 +836,7 @@ function createAskUserQuestionTool(ctx, config) {
648
836
  type: "array",
649
837
  required: true,
650
838
  items: { type: "string" },
651
- description: "Option labels the user had selected; empty with no custom means the question was left blank."
839
+ description: "Option labels the user had selected for this question."
652
840
  },
653
841
  custom: {
654
842
  type: "string",
@@ -694,7 +882,7 @@ function createAskUserQuestionTool(ctx, config) {
694
882
  }]
695
883
  },
696
884
  async execute(args, exec) {
697
- const timeoutSeconds = resolveTimeout(args.timeout, configValue(config.timeoutSeconds) ?? 120);
885
+ const timeoutSeconds = resolveTimeout(args.timeout ?? nestedTimeout(args.questions), configValue(config.timeoutSeconds) ?? 120);
698
886
  const infiniteEnabled = configValue(config.infiniteWait) ?? true;
699
887
  const draftFallbackEnabled = configValue(config.draftFallback) ?? true;
700
888
  const injectsDraft = injectsContext(configValue(config.fallback) ?? "both");
@@ -737,7 +925,12 @@ function createAskUserQuestionTool(ctx, config) {
737
925
  markCallSettled(exec.callId);
738
926
  }
739
927
  if (exec.agent === void 0) throw new Error("timed questions require a live agent");
740
- const timeoutMs = timeoutSeconds * 1e3;
928
+ const requestedTimeoutMs = timeoutSeconds * 1e3;
929
+ const parentCallId = exec.rootCallId === exec.callId ? void 0 : exec.rootCallId;
930
+ const parentRemaining = parentCallId === void 0 ? void 0 : runBudgetRemaining(parentCallId);
931
+ const usableMs = parentRemaining === void 0 ? void 0 : parentRemaining - PTC_BUDGET_MARGIN_MS;
932
+ if (usableMs !== void 0 && usableMs < 2e3) throw new Error(TIMEOUT_PENDING_BUDGET_NOTICE);
933
+ const timeoutMs = usableMs === void 0 ? requestedTimeoutMs : Math.min(requestedTimeoutMs, usableMs);
741
934
  registerCallDeadline(exec.callId, Date.now() + timeoutMs);
742
935
  registerCallQuestions(exec.callId, questions.map((question) => question.id));
743
936
  const waitController = new AbortController();
@@ -813,6 +1006,8 @@ function createAskUserQuestionTool(ctx, config) {
813
1006
  if (authority !== void 0 && draft.some((item) => item.index >= authority.length)) console.warn("[question-timeout-protection] 草稿的题目序号超出本次提问的题目数, 多余的部分已丢弃");
814
1007
  const mapped = [];
815
1008
  let dropped = 0;
1009
+ let remainingChars = MAX_DRAFT_TOTAL_CHARS;
1010
+ let truncated = false;
816
1011
  for (const item of draft) {
817
1012
  const question = questions[item.index];
818
1013
  if (question === void 0) {
@@ -821,10 +1016,25 @@ function createAskUserQuestionTool(ctx, config) {
821
1016
  }
822
1017
  const custom = item.custom?.trim() ?? "";
823
1018
  if (item.selected.length === 0 && custom === "") continue;
1019
+ const selected = [...item.selected];
1020
+ const questionLimit = Math.min(MAX_DRAFT_QUESTION_CHARS, remainingChars);
1021
+ const selectedChars = selected.reduce((sum, label) => sum + label.length, 0);
1022
+ if (selectedChars > questionLimit) {
1023
+ truncated = true;
1024
+ continue;
1025
+ }
1026
+ const room = questionLimit - selectedChars;
1027
+ const keptCustom = custom.length > room ? custom.slice(0, room) : custom;
1028
+ if (keptCustom.length !== custom.length) truncated = true;
1029
+ if (selected.length === 0 && keptCustom === "") {
1030
+ truncated = true;
1031
+ break;
1032
+ }
1033
+ remainingChars -= selectedChars + keptCustom.length;
824
1034
  mapped.push({
825
1035
  id: question.id,
826
- selected: [...item.selected],
827
- ...custom === "" ? {} : { custom }
1036
+ selected,
1037
+ ...keptCustom === "" ? {} : { custom: keptCustom }
828
1038
  });
829
1039
  }
830
1040
  if (dropped > 0) console.warn("[question-timeout-protection] 有 " + String(dropped) + " 条草稿对不上本次提问的题目, 已丢弃");
@@ -836,7 +1046,7 @@ function createAskUserQuestionTool(ctx, config) {
836
1046
  return {
837
1047
  pending: true,
838
1048
  callId,
839
- message: TIMEOUT_PENDING_DRAFT_NOTICE,
1049
+ message: truncated ? TIMEOUT_PENDING_DRAFT_NOTICE + TIMEOUT_PENDING_DRAFT_TRUNCATED_NOTICE : TIMEOUT_PENDING_DRAFT_NOTICE,
840
1050
  draft: mapped
841
1051
  };
842
1052
  }
@@ -1068,6 +1278,12 @@ const inject = [
1068
1278
  function apply(ctx, config) {
1069
1279
  const service = new QuestionTimeoutService(ctx, config);
1070
1280
  service.start();
1281
+ let ptcDefaultBudgetMs = DEFAULT_PTC_BUDGET_MS;
1282
+ ctx.inject(["ptcRuntime"], (scoped) => {
1283
+ const value = (scoped ?? ctx).ptcRuntime?.timeout?.defaultMs;
1284
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) ptcDefaultBudgetMs = value;
1285
+ });
1286
+ ctx.effect(() => installRunBudgetTracking(ctx, () => ptcDefaultBudgetMs));
1071
1287
  let syncStarted = false;
1072
1288
  ctx.inject(["webServer"], (scoped) => {
1073
1289
  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.3",
3
+ "version": "0.2.0",
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.3-rc.1"
14
+ "dsh": ">=0.2.1-rc.1 <0.2.2-rc.0 || >=0.2.2-rc.0 <0.2.3-rc.1"
15
15
  },
16
16
  "main": "./dist/index.mjs",
17
17
  "types": "./dist/index.d.mts",
@@ -39,10 +39,10 @@
39
39
  "scripts": {
40
40
  "build": "tsdown",
41
41
  "dev": "tsdown --watch",
42
- "pack:release": "node scripts/check-translation.mjs && tsdown && pnpm pack --ignore-scripts && node scripts/pack-release.mjs --strict",
42
+ "pack:release": "node scripts/check-translation.mjs --strict && tsdown && pnpm pack --ignore-scripts && node scripts/pack-release.mjs --strict && node scripts/verify-tarball.mjs",
43
43
  "prepare": "node scripts/check-translation.mjs && tsdown",
44
- "prepack": "node scripts/check-translation.mjs && tsdown",
45
- "postpack": "node scripts/pack-release.mjs",
44
+ "prepack": "node scripts/check-translation.mjs --strict && tsdown",
45
+ "postpack": "node scripts/pack-release.mjs && node scripts/verify-tarball.mjs --if-present",
46
46
  "typecheck": "tsc --noEmit",
47
47
  "check:translation": "node scripts/check-translation.mjs"
48
48
  },
@@ -51,9 +51,9 @@
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.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"
54
+ "@deepseek-ai/dsh-agent": ">=0.2.1-rc.1 <0.2.2-rc.0 || >=0.2.2-rc.0 <0.2.3-rc.1",
55
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.1 <0.2.2-rc.0 || >=0.2.2-rc.0 <0.2.3-rc.1",
56
+ "@deepseek-ai/dsh-user-questions": ">=0.2.1-rc.1 <0.2.2-rc.0 || >=0.2.2-rc.0 <0.2.3-rc.1"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@deepseek-ai/cordis": "~4.1.0",
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.3
2
+ for=v0.2.0
3
3
  lang=zh-CN
4
4
  name=简体中文
5
- endtime=2026-11-12 18:50:00+08:00
5
+ endtime=2026-11-25 17: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=卡片增强
@@ -31,6 +31,8 @@ control.infiniteWait=无限等待
31
31
  control.autoInfiniteLabel=问答自动无限等待
32
32
  control.autoInfiniteOn=开
33
33
  control.autoInfiniteOff=关
34
+ control.customRadio=自定义回答
35
+ control.customHint=已保留自定义内容: {text}(点这里选用)
34
36
  control.autoInfiniteTitle=开启后每次提问都自动进入无限等待, 关闭后回到插件的计时行为
35
37
  bubble.draftLabel=提问·超时草稿
36
38
  draft.selected=已选: {items}
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.3
2
+ for=v0.2.0
3
3
  lang=en-US
4
4
  name=English (US)
5
- endtime=2026-11-12 19:20:00+08:00
5
+ endtime=2026-11-25 17: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
@@ -31,6 +31,8 @@ control.infiniteWait=Wait indefinitely
31
31
  control.autoInfiniteLabel=Auto wait indefinitely
32
32
  control.autoInfiniteOn=On
33
33
  control.autoInfiniteOff=Off
34
+ control.customRadio=Custom answer
35
+ control.customHint=Custom answer kept: {text} (click to use it)
34
36
  control.autoInfiniteTitle=When on, every question enters indefinite wait automatically; when off, the plugin countdown applies
35
37
  bubble.draftLabel=Question · timed-out draft
36
38
  draft.selected=Selected: {items}
@@ -1,8 +1,8 @@
1
1
  [meta]
2
- for=v0.1.3
2
+ for=v0.2.0
3
3
  lang=zh-CN
4
4
  name=简体中文
5
- endtime=2026-11-12 18:50:00+08:00
5
+ endtime=2026-11-25 17: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=卡片增强
@@ -31,6 +31,8 @@ control.infiniteWait=无限等待
31
31
  control.autoInfiniteLabel=问答自动无限等待
32
32
  control.autoInfiniteOn=开
33
33
  control.autoInfiniteOff=关
34
+ control.customRadio=自定义回答
35
+ control.customHint=已保留自定义内容: {text}(点这里选用)
34
36
  control.autoInfiniteTitle=开启后每次提问都自动进入无限等待, 关闭后回到插件的计时行为
35
37
  bubble.draftLabel=提问·超时草稿
36
38
  draft.selected=已选: {items}