dsh-question-timeout-protection 0.0.0-stage → 0.1.2

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 ADDED
@@ -0,0 +1,1095 @@
1
+ import Schema from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { randomBytes } from "node:crypto";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ // src/constants.ts
8
+ /** 插件包名 */
9
+ const PLUGIN_NAME = "dsh-question-timeout-protection";
10
+ /** 默认语言(翻译回退与初始语言) */
11
+ const DEFAULT_LANGUAGE = "zh-CN";
12
+ /** 回退语言,翻译未命中时使用 */
13
+ const FALLBACK_LANGUAGE = "zh-CN";
14
+ /** 翻译文件目录,相对插件包根目录 */
15
+ const TRANSLATION_DIR = "src/translation";
16
+ /** 兜底范围默认值(界面保留草稿并把超时草稿注入上下文) */
17
+ const DEFAULT_FALLBACK_MODE = "both";
18
+ /** 提问等待时长上限(秒,与宿主平台定时器上限对齐) */
19
+ const MAX_TIMEOUT_SECONDS = 2147483;
20
+ /** 本插件接管的工具名,与宿主提问工具同名以就近遮蔽 */
21
+ const ASK_USER_TOOL_NAME = "ask_user_question";
22
+ /**
23
+ * timed 提问的工具参数名。
24
+ * 宿主提问投影依据记录的工具参数中是否存在该字段判定调用为 timed,
25
+ * 因此本插件定义的工具必须声明它,否则超时后的问题不会进入 continued 态。
26
+ */
27
+ const TIMED_TIMEOUT_PARAMETER = "timeout";
28
+ /**
29
+ * 超时后随 pending 结果返回给模型的说明。
30
+ * 语义要点: 只说明本轮提问已超时、用户没有正式提交, 不对草稿做任何断言 ——
31
+ * 草稿为空时不该告诉模型"草稿保留了下来"; 有草稿时草稿走 draft 字段随本结果一起回来。
32
+ */
33
+ const TIMEOUT_PENDING_NOTICE = "该轮提问已超时,用户没有正式提交; 请在回复末尾告知用户这一点。";
34
+ /**
35
+ * 没有收到任何草稿快照时的说明。
36
+ * 与「收到空草稿」不同: 后者表示用户确实没写, 前者是快照没送达, 模型不能据此断定用户没输入。
37
+ */
38
+ const TIMEOUT_PENDING_MISSING_NOTICE = "该轮提问已超时,用户没有正式提交; 本轮没有收到草稿快照(草稿通道不可达或页面未打开), 因此拿不到超时前的输入内容, 请不要据此断言用户没有输入, 并在回复末尾告知用户这次提问已超时。";
39
+ /**
40
+ * 有草稿时随 pending 结果返回给模型的说明。
41
+ * 草稿本身放在 pending 结果的 draft 字段里, 这里只说明它的存在与用法,
42
+ * 避免模型把整段说明当成草稿内容。
43
+ */
44
+ const TIMEOUT_PENDING_DRAFT_NOTICE = "该轮提问已超时,用户没有正式提交; 超时前留下的草稿已随本结果带回, 内容见 draft 字段, 请据此继续任务, 并在最后告知用户这次超时以及你对草稿的处理决策。";
45
+ /** 是否把超时草稿注入对话上下文 */
46
+ function injectsContext(mode) {
47
+ return mode === "context" || mode === "both";
48
+ }
49
+ /** 工具到期后等待客户端上报草稿的宽限时长(毫秒) */
50
+ const DRAFT_GRACE_MS = 3e3;
51
+ /** 客户端状态同步端点路径 */
52
+ const SYNC_PATH = "/question-timeout-protection/state";
53
+ // src/config-value.ts
54
+ /** 读取 volatile 字段的当前值, 兼容普通值 */
55
+ function configValue(value) {
56
+ if (typeof value === "object" && value !== null && "get" in value) return value.get();
57
+ return value;
58
+ }
59
+ // src/config.ts
60
+ const Config = Schema.object({
61
+ fallback: Schema.union([
62
+ "ui",
63
+ "context",
64
+ "both"
65
+ ]).default(DEFAULT_FALLBACK_MODE).volatile(),
66
+ warningSeconds: Schema.number().min(1).max(60).default(5).volatile(),
67
+ timeoutSeconds: Schema.number().min(1).max(MAX_TIMEOUT_SECONDS).default(120).volatile(),
68
+ cardEnhancements: Schema.boolean().default(true).volatile(),
69
+ infiniteWait: Schema.boolean().default(true).volatile(),
70
+ draftFallback: Schema.boolean().default(true).volatile()
71
+ });
72
+ // src/sync/server.ts
73
+ const infiniteCalls = /* @__PURE__ */ new Map();
74
+ const MAX_BODY_LENGTH = 262144;
75
+ const CALL_ID_PATTERN = /^[^\u0000-\u0020\u007f]{1,200}$/;
76
+ const MAX_INFINITE_CALLS = 512;
77
+ const draftReports = /* @__PURE__ */ new Map();
78
+ const draftReportedAt = /* @__PURE__ */ new Map();
79
+ const DRAFT_REPORT_TTL_MS = 3e5;
80
+ const settledCalls = /* @__PURE__ */ new Map();
81
+ const syncToken = randomBytes(24).toString("hex");
82
+ const callDeadlines = /* @__PURE__ */ new Map();
83
+ const MAX_DRAFT_ANSWERS = 64;
84
+ let truncationWarned = false;
85
+ const MAX_DRAFT_SNAPSHOTS = 256;
86
+ const MAX_TRACKED_CALLS = 512;
87
+ const TRACKED_CALL_TTL_MS = 9e5;
88
+ const SETTLE_MS = 600;
89
+ const POLL_INTERVAL_MS = 100;
90
+ function rememberInfiniteCall(callId) {
91
+ if (infiniteCalls.size >= MAX_INFINITE_CALLS && !infiniteCalls.has(callId)) {
92
+ const oldest = infiniteCalls.keys().next();
93
+ if (!oldest.done) infiniteCalls.delete(oldest.value);
94
+ }
95
+ infiniteCalls.set(callId, Date.now());
96
+ }
97
+ function reportDraft(callId, answers) {
98
+ if (!callDeadlines.has(callId)) return false;
99
+ if (draftReports.size >= MAX_DRAFT_SNAPSHOTS && !draftReports.has(callId)) {
100
+ const oldest = draftReports.keys().next();
101
+ if (!oldest.done) {
102
+ draftReports.delete(oldest.value);
103
+ draftReportedAt.delete(oldest.value);
104
+ }
105
+ }
106
+ draftReports.set(callId, answers);
107
+ draftReportedAt.set(callId, Date.now());
108
+ return true;
109
+ }
110
+ async function awaitDraft(callId, timeoutMs) {
111
+ const deadline = Date.now() + timeoutMs;
112
+ while (Date.now() < deadline) {
113
+ if (infiniteCalls.has(callId)) return;
114
+ const reported = draftReports.get(callId);
115
+ if (reported !== void 0) {
116
+ await sleep(SETTLE_MS);
117
+ if (infiniteCalls.has(callId)) return void 0;
118
+ const latest = draftReports.get(callId);
119
+ draftReports.delete(callId);
120
+ draftReportedAt.delete(callId);
121
+ return latest ?? reported;
122
+ }
123
+ await sleep(POLL_INTERVAL_MS);
124
+ }
125
+ draftReports.delete(callId);
126
+ draftReportedAt.delete(callId);
127
+ }
128
+ function clearDraft(callId) {
129
+ draftReports.delete(callId);
130
+ draftReportedAt.delete(callId);
131
+ }
132
+ function markCallSettled(callId) {
133
+ settledCalls.set(callId, Date.now());
134
+ while (settledCalls.size > MAX_TRACKED_CALLS) {
135
+ const oldest = settledCalls.keys().next();
136
+ if (oldest.done) break;
137
+ settledCalls.delete(oldest.value);
138
+ }
139
+ }
140
+ function sleep(ms) {
141
+ return new Promise((resolve) => {
142
+ setTimeout(resolve, ms);
143
+ });
144
+ }
145
+ function normalizeAnswers(value) {
146
+ if (!Array.isArray(value)) return [];
147
+ if (value.length > MAX_DRAFT_ANSWERS && !truncationWarned) {
148
+ truncationWarned = true;
149
+ console.warn("[question-timeout-protection] 单次上报的草稿条目数为 " + String(value.length) + ", 超过上限 " + String(MAX_DRAFT_ANSWERS) + ", 超出的部分已丢弃");
150
+ }
151
+ const answers = [];
152
+ for (const entry of value.slice(0, MAX_DRAFT_ANSWERS)) {
153
+ if (typeof entry !== "object" || entry === null) continue;
154
+ const item = entry;
155
+ if (typeof item.index !== "number" || !Number.isInteger(item.index) || item.index < 0) continue;
156
+ const selected = Array.isArray(item.selected) ? item.selected.filter((label) => typeof label === "string") : [];
157
+ const custom = typeof item.custom === "string" ? item.custom : void 0;
158
+ answers.push({
159
+ index: item.index,
160
+ selected,
161
+ ...custom === void 0 || custom.trim() === "" ? {} : { custom }
162
+ });
163
+ }
164
+ return answers;
165
+ }
166
+ function sweepTrackedCalls() {
167
+ const now = Date.now();
168
+ for (const [callId, deadline] of callDeadlines) if (now - deadline > TRACKED_CALL_TTL_MS) callDeadlines.delete(callId);
169
+ for (const [callId, settledAt] of settledCalls) if (now - settledAt > TRACKED_CALL_TTL_MS) settledCalls.delete(callId);
170
+ for (const [callId, reportedAt] of draftReportedAt) {
171
+ if (now - reportedAt <= DRAFT_REPORT_TTL_MS) continue;
172
+ draftReportedAt.delete(callId);
173
+ draftReports.delete(callId);
174
+ }
175
+ for (const callId of callQuestionOrders.keys()) if (!callDeadlines.has(callId)) callQuestionOrders.delete(callId);
176
+ for (const [callId, registeredAt] of infiniteCalls) if (now - registeredAt > TRACKED_CALL_TTL_MS) infiniteCalls.delete(callId);
177
+ while (callDeadlines.size > MAX_TRACKED_CALLS) {
178
+ const oldest = callDeadlines.keys().next();
179
+ if (oldest.done) break;
180
+ callDeadlines.delete(oldest.value);
181
+ }
182
+ while (callQuestionOrders.size > MAX_TRACKED_CALLS) {
183
+ const oldest = callQuestionOrders.keys().next();
184
+ if (oldest.done) break;
185
+ callQuestionOrders.delete(oldest.value);
186
+ }
187
+ }
188
+ function isHostOrigin(origin, host) {
189
+ if (host === void 0 || host === "") return false;
190
+ const source = parseHostPort(origin);
191
+ if (source === void 0) return false;
192
+ const request = parseHostPort(source.protocol + "//" + host);
193
+ if (request === void 0) return false;
194
+ return source.host === request.host && source.port === request.port;
195
+ }
196
+ function parseHostPort(value) {
197
+ try {
198
+ const parsed = new URL(value);
199
+ if (parsed.hostname === "") return void 0;
200
+ const port = parsed.port === "" ? parsed.protocol === "https:" ? "443" : "80" : parsed.port;
201
+ return {
202
+ host: normalizeHost(parsed.hostname),
203
+ port,
204
+ protocol: parsed.protocol
205
+ };
206
+ } catch {
207
+ return;
208
+ }
209
+ }
210
+ function normalizeHost(value) {
211
+ return value === "localhost" ? "127.0.0.1" : value;
212
+ }
213
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
214
+ "127.0.0.1",
215
+ "localhost",
216
+ "[::1]"
217
+ ]);
218
+ function isLoopbackHost(host) {
219
+ if (host === void 0 || host === "") return false;
220
+ try {
221
+ const parsed = new URL("http://" + host);
222
+ if (parsed.username !== "" || parsed.password !== "") return false;
223
+ if (parsed.pathname !== "/" || parsed.search !== "" || parsed.hash !== "") return false;
224
+ return LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase());
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+ function serveToken(request, response) {
230
+ if (request.method !== "GET" || request.url !== "/question-timeout-protection/state-token") return false;
231
+ if (!isLoopbackHost(request.headers.host)) {
232
+ response.writeHead(403);
233
+ response.end();
234
+ return true;
235
+ }
236
+ const origin = request.headers.origin;
237
+ if (typeof origin === "string") {
238
+ if (!isHostOrigin(origin, request.headers.host)) {
239
+ response.writeHead(403);
240
+ response.end();
241
+ return true;
242
+ }
243
+ response.setHeader("Access-Control-Allow-Origin", origin);
244
+ response.setHeader("Vary", "Origin");
245
+ }
246
+ response.writeHead(200, {
247
+ "content-type": "application/json",
248
+ "cache-control": "no-store"
249
+ });
250
+ response.end(JSON.stringify({ token: syncToken }));
251
+ return true;
252
+ }
253
+ function handleStateRequest(request, response) {
254
+ if (!isLoopbackHost(request.headers.host)) {
255
+ response.writeHead(403);
256
+ response.end();
257
+ return;
258
+ }
259
+ const origin = request.headers.origin;
260
+ if (typeof origin === "string") {
261
+ if (!isHostOrigin(origin, request.headers.host)) {
262
+ response.writeHead(403);
263
+ response.end();
264
+ return;
265
+ }
266
+ response.setHeader("Access-Control-Allow-Origin", origin);
267
+ response.setHeader("Vary", "Origin");
268
+ }
269
+ response.setHeader("Access-Control-Allow-Headers", "content-type, x-qtp-token");
270
+ response.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
271
+ if (request.method === "OPTIONS") {
272
+ if (typeof origin === "string" && !isHostOrigin(origin, request.headers.host)) {
273
+ response.writeHead(403);
274
+ response.end();
275
+ return;
276
+ }
277
+ response.writeHead(204);
278
+ response.end();
279
+ return;
280
+ }
281
+ if (serveToken(request, response)) return;
282
+ const token = request.headers["x-qtp-token"];
283
+ if (typeof token !== "string" || token !== syncToken) {
284
+ response.writeHead(401);
285
+ response.end();
286
+ return;
287
+ }
288
+ if (request.method === "GET" && request.url === "/question-timeout-protection/state-state") {
289
+ response.writeHead(200, { "content-type": "application/json" });
290
+ response.end(JSON.stringify({ calls: [...infiniteCalls.keys()] }));
291
+ return;
292
+ }
293
+ if (request.method !== "POST" || request.url !== "/question-timeout-protection/state") {
294
+ response.writeHead(404);
295
+ response.end();
296
+ return;
297
+ }
298
+ const chunks = [];
299
+ let received = 0;
300
+ let oversized = false;
301
+ request.on("data", (chunk) => {
302
+ if (oversized) return;
303
+ chunks.push(chunk);
304
+ received += chunk.length;
305
+ if (received > MAX_BODY_LENGTH) {
306
+ oversized = true;
307
+ response.writeHead(413, { "content-type": "application/json" });
308
+ response.end(JSON.stringify({
309
+ ok: false,
310
+ reason: "too-large"
311
+ }));
312
+ chunks.length = 0;
313
+ request.destroy();
314
+ }
315
+ });
316
+ request.on("error", (error) => {
317
+ if (oversized) return;
318
+ console.warn("[question-timeout-protection] 状态上报请求体读取失败, 本次上报已丢弃", String(error));
319
+ });
320
+ request.on("aborted", () => {
321
+ if (oversized) return;
322
+ console.warn("[question-timeout-protection] 状态上报请求被客户端中断, 本次上报已丢弃");
323
+ });
324
+ request.on("end", () => {
325
+ if (oversized) return;
326
+ const body = Buffer.concat(chunks).toString("utf8");
327
+ try {
328
+ const parsed = JSON.parse(body);
329
+ if (typeof parsed.callId !== "string" || !CALL_ID_PATTERN.test(parsed.callId)) {
330
+ response.writeHead(400);
331
+ response.end();
332
+ return;
333
+ }
334
+ if (parsed.infinite === false) clearInfiniteWait(parsed.callId);
335
+ else if (parsed.infinite === true) {
336
+ if (settledCalls.has(parsed.callId)) {
337
+ response.writeHead(200, { "content-type": "application/json" });
338
+ response.end(JSON.stringify({
339
+ ok: false,
340
+ reason: "expired"
341
+ }));
342
+ return;
343
+ }
344
+ const authority = callDeadlines.get(parsed.callId);
345
+ const clientDeadline = typeof parsed.deadline === "number" && Number.isFinite(parsed.deadline) ? parsed.deadline : void 0;
346
+ const effective = authority ?? clientDeadline;
347
+ if (effective !== void 0 && Date.now() > effective) {
348
+ response.writeHead(200, { "content-type": "application/json" });
349
+ response.end(JSON.stringify({
350
+ ok: false,
351
+ reason: "expired"
352
+ }));
353
+ return;
354
+ }
355
+ rememberInfiniteCall(parsed.callId);
356
+ } else if (Array.isArray(parsed.answers)) {
357
+ if (!reportDraft(parsed.callId, normalizeAnswers(parsed.answers))) {
358
+ response.writeHead(200, { "content-type": "application/json" });
359
+ response.end(JSON.stringify({
360
+ ok: true,
361
+ ignored: true
362
+ }));
363
+ return;
364
+ }
365
+ } else {
366
+ response.writeHead(400);
367
+ response.end();
368
+ return;
369
+ }
370
+ response.writeHead(200, { "content-type": "application/json" });
371
+ response.end("{\"ok\":true}");
372
+ } catch {
373
+ response.writeHead(400);
374
+ response.end();
375
+ }
376
+ });
377
+ }
378
+ /**
379
+ * 把状态端点挂到宿主自带的 HTTP 服务上。
380
+ * 同源注册后不需要 CORS, 也不会与另一个 dsh 实例的固定端口互相抢请求。
381
+ * @param webServer 宿主 WebServer 服务, 提供 register 与 getOrigin
382
+ * @returns 注销函数
383
+ */
384
+ function registerQuestionSyncRoute(webServer) {
385
+ if (detachRoutes === void 0) {
386
+ const offs = [];
387
+ try {
388
+ offs.push(webServer.register({
389
+ kind: "exact",
390
+ path: SYNC_PATH,
391
+ handler: handleStateRequest
392
+ }));
393
+ offs.push(webServer.register({
394
+ kind: "exact",
395
+ path: SYNC_PATH + "-token",
396
+ handler: handleStateRequest
397
+ }));
398
+ offs.push(webServer.register({
399
+ kind: "exact",
400
+ path: SYNC_PATH + "-state",
401
+ handler: handleStateRequest
402
+ }));
403
+ } catch (error) {
404
+ for (const off of offs.reverse()) try {
405
+ off();
406
+ } catch {}
407
+ throw error;
408
+ }
409
+ detachRoutes = () => {
410
+ for (const off of offs.reverse()) try {
411
+ off();
412
+ } catch {}
413
+ };
414
+ syncChannelReady = true;
415
+ console.info("[question-timeout-protection] 状态同步路由已挂在宿主 HTTP 服务上: " + SYNC_PATH);
416
+ }
417
+ channelUsers += 1;
418
+ let released = false;
419
+ return () => {
420
+ if (released) return;
421
+ released = true;
422
+ channelUsers = Math.max(0, channelUsers - 1);
423
+ if (channelUsers > 0) return;
424
+ detachRoutes?.();
425
+ detachRoutes = void 0;
426
+ clearSyncState();
427
+ };
428
+ }
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
+ let syncChannelReady = false;
439
+ let channelUsers = 0;
440
+ let detachRoutes;
441
+ function hasSyncChannel() {
442
+ return syncChannelReady;
443
+ }
444
+ function registerCallDeadline(callId, deadline) {
445
+ callDeadlines.set(callId, deadline);
446
+ sweepTrackedCalls();
447
+ }
448
+ const callQuestionOrders = /* @__PURE__ */ new Map();
449
+ function registerCallQuestions(callId, ids) {
450
+ callQuestionOrders.set(callId, [...ids]);
451
+ sweepTrackedCalls();
452
+ }
453
+ function clearCallQuestions(callId) {
454
+ callQuestionOrders.delete(callId);
455
+ }
456
+ function callQuestionOrder(callId) {
457
+ return callQuestionOrders.get(callId);
458
+ }
459
+ function clearCallDeadline(callId) {
460
+ callDeadlines.delete(callId);
461
+ }
462
+ /** 该调用是否已选择无限等待 */
463
+ function isInfiniteWait(callId) {
464
+ return infiniteCalls.has(callId);
465
+ }
466
+ /** 清理一个调用的状态 */
467
+ function clearInfiniteWait(callId) {
468
+ infiniteCalls.delete(callId);
469
+ }
470
+ /** 清空状态通道里登记的全部状态 */
471
+ function stopQuestionSync() {
472
+ if (channelUsers > 0) return;
473
+ clearSyncState();
474
+ }
475
+ // 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.";
477
+ const QUESTIONS_DESCRIPTION = "Questions to ask the user.";
478
+ function resolveTimeout(requested, fallback) {
479
+ const raw = requested ?? fallback;
480
+ if (raw === -1) return -1;
481
+ const value = Number.isFinite(raw) ? Math.round(raw) : raw;
482
+ if (!Number.isInteger(value) || value < 1 || value > 2147483) throw new Error(`timeout must be -1 or an integer between ${String(1)} and ${String(MAX_TIMEOUT_SECONDS)} seconds`);
483
+ return value;
484
+ }
485
+ function linkSignals(first, second) {
486
+ const controller = new AbortController();
487
+ const abort = () => {
488
+ if (!controller.signal.aborted) controller.abort();
489
+ };
490
+ const bound = [];
491
+ if (first?.aborted === true) abort();
492
+ else if (first !== void 0) {
493
+ first.addEventListener("abort", abort, { once: true });
494
+ bound.push(first);
495
+ }
496
+ if (second.aborted) abort();
497
+ else {
498
+ second.addEventListener("abort", abort, { once: true });
499
+ bound.push(second);
500
+ }
501
+ return {
502
+ signal: controller.signal,
503
+ dispose: () => {
504
+ for (const target of bound) target.removeEventListener("abort", abort);
505
+ bound.length = 0;
506
+ }
507
+ };
508
+ }
509
+ function assertQuestionsPresent(questions) {
510
+ if (questions.length === 0) throw new Error("questions must contain at least one question");
511
+ }
512
+ function assertUniqueQuestionIds(questions) {
513
+ const seen = /* @__PURE__ */ new Set();
514
+ for (const question of questions) {
515
+ const id = question.id.trim();
516
+ if (id === "") throw new Error("question id must not be empty");
517
+ if (seen.has(id)) throw new Error(`question id ${JSON.stringify(id)} must be unique within this call`);
518
+ seen.add(id);
519
+ }
520
+ }
521
+ /**
522
+ * 创建本插件的提问工具定义。
523
+ * @param ctx 注册工具的上下文(逐 agent 作用域)
524
+ * @param config 插件配置,提供缺省等待时长
525
+ * @returns 可直接注册到工具注册表的定义
526
+ */
527
+ function createAskUserQuestionTool(ctx, config) {
528
+ return defineTool({
529
+ name: ASK_USER_TOOL_NAME,
530
+ description: TOOL_DESCRIPTION,
531
+ parameters: {
532
+ questions: {
533
+ type: "array",
534
+ required: true,
535
+ description: QUESTIONS_DESCRIPTION,
536
+ items: {
537
+ type: "object",
538
+ additionalProperties: true,
539
+ properties: {
540
+ id: {
541
+ type: "string",
542
+ required: true,
543
+ description: "Stable id for this question; it is echoed in the answer."
544
+ },
545
+ question: {
546
+ type: "string",
547
+ required: true,
548
+ description: "The specific question to ask the user."
549
+ },
550
+ header: {
551
+ type: "string",
552
+ description: "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"."
553
+ },
554
+ detail: {
555
+ type: "string",
556
+ description: "Optional supporting detail rendered with the question but kept out of the option labels, such as a plan or a long explanation."
557
+ },
558
+ intent: {
559
+ type: "object",
560
+ additionalProperties: true,
561
+ description: "Optional presentation intent for capable UIs. Currently the only tag is plan-review, which needs approve (the option label that accepts it); a UI that does not know the tag renders the generic option list.",
562
+ properties: {
563
+ kind: {
564
+ type: "string",
565
+ required: true,
566
+ description: "Intent tag. Currently only \"plan-review\"."
567
+ },
568
+ approve: {
569
+ type: "string",
570
+ description: "For plan-review: the option label that approves the plan; every other option declines it."
571
+ },
572
+ callId: {
573
+ type: "string",
574
+ description: "For plan-review: the logged tool call whose arguments contain the reviewed plan."
575
+ }
576
+ }
577
+ },
578
+ options: {
579
+ type: "array",
580
+ description: "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.",
581
+ items: {
582
+ type: "object",
583
+ additionalProperties: true,
584
+ properties: {
585
+ label: {
586
+ type: "string",
587
+ required: true,
588
+ description: "Short user-facing option label."
589
+ },
590
+ description: {
591
+ type: "string",
592
+ description: "One sentence explaining the tradeoff or impact."
593
+ }
594
+ }
595
+ }
596
+ },
597
+ multi_select: {
598
+ type: "boolean",
599
+ description: "Whether the user may select more than one option. Defaults to false."
600
+ }
601
+ }
602
+ }
603
+ },
604
+ [TIMED_TIMEOUT_PARAMETER]: {
605
+ 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.`
607
+ }
608
+ },
609
+ output: {
610
+ schema: { oneOf: [{
611
+ type: "object",
612
+ additionalProperties: false,
613
+ properties: {
614
+ pending: {
615
+ type: "boolean",
616
+ enum: [true],
617
+ required: true,
618
+ description: "True when the foreground wait expired before the user submitted an answer batch."
619
+ },
620
+ callId: {
621
+ type: "string",
622
+ required: true,
623
+ description: "Tool call whose unanswered questions remain pending."
624
+ },
625
+ message: {
626
+ type: "string",
627
+ required: true,
628
+ description: "How to continue while the questions stay answerable."
629
+ },
630
+ draftMissing: {
631
+ type: "boolean",
632
+ enum: [true],
633
+ description: "True when no draft snapshot ever reached the plugin, so an absent draft does not mean the user typed nothing."
634
+ },
635
+ draft: {
636
+ type: "array",
637
+ description: "Unsubmitted draft the user had entered when the wait expired; one item per question, empty when there was no draft.",
638
+ items: {
639
+ type: "object",
640
+ additionalProperties: false,
641
+ properties: {
642
+ id: {
643
+ type: "string",
644
+ required: true,
645
+ description: "Stable question id echoed from the request."
646
+ },
647
+ selected: {
648
+ type: "array",
649
+ required: true,
650
+ items: { type: "string" },
651
+ description: "Option labels the user had selected; empty with no custom means the question was left blank."
652
+ },
653
+ custom: {
654
+ type: "string",
655
+ description: "Free-form text the user had typed for this question."
656
+ }
657
+ }
658
+ }
659
+ }
660
+ }
661
+ }, {
662
+ type: "object",
663
+ additionalProperties: false,
664
+ properties: { answers: {
665
+ type: "array",
666
+ required: true,
667
+ description: "Submitted answer batch with one item per question.",
668
+ items: {
669
+ type: "object",
670
+ additionalProperties: false,
671
+ properties: {
672
+ id: {
673
+ type: "string",
674
+ required: true,
675
+ description: "Stable question id echoed from the request."
676
+ },
677
+ selected: {
678
+ type: "array",
679
+ required: true,
680
+ items: { type: "string" },
681
+ description: "Selected option labels; empty with no custom means the question was skipped."
682
+ },
683
+ custom: {
684
+ type: "string",
685
+ description: "Optional free-form answer; omitted for a skipped question."
686
+ }
687
+ }
688
+ }
689
+ } }
690
+ }] },
691
+ render: (_args, value) => [{
692
+ type: "text",
693
+ text: JSON.stringify(value)
694
+ }]
695
+ },
696
+ async execute(args, exec) {
697
+ const timeoutSeconds = resolveTimeout(args.timeout, configValue(config.timeoutSeconds) ?? 120);
698
+ const infiniteEnabled = configValue(config.infiniteWait) ?? true;
699
+ const draftFallbackEnabled = configValue(config.draftFallback) ?? true;
700
+ const injectsDraft = injectsContext(configValue(config.fallback) ?? "both");
701
+ assertQuestionsPresent(args.questions);
702
+ assertUniqueQuestionIds(args.questions);
703
+ const toIntent = (value) => {
704
+ if (value === void 0 || value.kind !== "plan-review") return void 0;
705
+ if (typeof value.approve !== "string" || value.approve === "") return void 0;
706
+ return {
707
+ kind: "plan-review",
708
+ approve: value.approve
709
+ };
710
+ };
711
+ const questions = args.questions.map((question) => {
712
+ const intent = toIntent(question.intent);
713
+ return {
714
+ id: question.id,
715
+ question: question.question,
716
+ ...question.header === void 0 ? {} : { header: question.header },
717
+ ...question.detail === void 0 ? {} : { detail: question.detail },
718
+ ...question.options === void 0 ? {} : { options: question.options.map((option) => ({ ...option })) },
719
+ ...question.multi_select === void 0 ? {} : { multiSelect: question.multi_select },
720
+ ...intent === void 0 ? {} : { intent }
721
+ };
722
+ });
723
+ if (timeoutSeconds === -1) try {
724
+ return { answers: (await ctx.userQuestions.ask({
725
+ questions,
726
+ ...exec.agent === void 0 ? {} : { agent: exec.agent },
727
+ signal: exec.signal,
728
+ wait: { callId: exec.callId }
729
+ })).answers.map((answer) => ({
730
+ id: answer.id,
731
+ selected: [...answer.selected],
732
+ ...answer.custom === void 0 ? {} : { custom: answer.custom }
733
+ })) };
734
+ } finally {
735
+ clearDraft(exec.callId);
736
+ clearCallQuestions(exec.callId);
737
+ markCallSettled(exec.callId);
738
+ }
739
+ if (exec.agent === void 0) throw new Error("timed questions require a live agent");
740
+ const timeoutMs = timeoutSeconds * 1e3;
741
+ registerCallDeadline(exec.callId, Date.now() + timeoutMs);
742
+ registerCallQuestions(exec.callId, questions.map((question) => question.id));
743
+ const waitController = new AbortController();
744
+ const linked = linkSignals(exec.signal, waitController.signal);
745
+ const waitSignal = linked.signal;
746
+ const wait = ctx.userQuestions.askTimed({
747
+ questions,
748
+ agent: exec.agent,
749
+ signal: waitSignal
750
+ }, exec.callId, timeoutMs);
751
+ wait.catch(() => void 0);
752
+ let timer;
753
+ const expired = new Promise((resolve) => {
754
+ timer = setTimeout(() => resolve({
755
+ pending: true,
756
+ callId: exec.callId
757
+ }), timeoutMs);
758
+ });
759
+ const toAnswers = (result) => ({ answers: result.answers.map((answer) => ({
760
+ id: answer.id,
761
+ selected: [...answer.selected],
762
+ ...answer.custom === void 0 ? {} : { custom: answer.custom }
763
+ })) });
764
+ const draftCache = /* @__PURE__ */ new Map();
765
+ const forgetDraft = (callId) => {
766
+ draftCache.delete(callId);
767
+ };
768
+ const loadDraft = (callId) => {
769
+ const cached = draftCache.get(callId);
770
+ if (cached !== void 0) return cached;
771
+ const created = awaitDraft(callId, DRAFT_GRACE_MS);
772
+ draftCache.set(callId, created);
773
+ return created;
774
+ };
775
+ async function pendingResult(callId, checkInfinite) {
776
+ if (checkInfinite && infiniteEnabled && isInfiniteWait(callId)) {
777
+ forgetDraft(callId);
778
+ return null;
779
+ }
780
+ if (!draftFallbackEnabled) return {
781
+ pending: true,
782
+ callId,
783
+ message: TIMEOUT_PENDING_NOTICE
784
+ };
785
+ if (!injectsDraft) return {
786
+ pending: true,
787
+ callId,
788
+ message: TIMEOUT_PENDING_NOTICE
789
+ };
790
+ if (!hasSyncChannel()) return {
791
+ pending: true,
792
+ callId,
793
+ message: TIMEOUT_PENDING_MISSING_NOTICE,
794
+ draftMissing: true
795
+ };
796
+ const draft = await loadDraft(callId);
797
+ if (checkInfinite && infiniteEnabled && isInfiniteWait(callId)) {
798
+ forgetDraft(callId);
799
+ return null;
800
+ }
801
+ if (draft === void 0) return {
802
+ pending: true,
803
+ callId,
804
+ message: TIMEOUT_PENDING_MISSING_NOTICE,
805
+ draftMissing: true
806
+ };
807
+ if (draft.length === 0) return {
808
+ pending: true,
809
+ callId,
810
+ message: TIMEOUT_PENDING_NOTICE
811
+ };
812
+ const authority = callQuestionOrder(callId);
813
+ if (authority !== void 0 && draft.some((item) => item.index >= authority.length)) console.warn("[question-timeout-protection] 草稿的题目序号超出本次提问的题目数, 多余的部分已丢弃");
814
+ const mapped = [];
815
+ let dropped = 0;
816
+ for (const item of draft) {
817
+ const question = questions[item.index];
818
+ if (question === void 0) {
819
+ dropped += 1;
820
+ continue;
821
+ }
822
+ const custom = item.custom?.trim() ?? "";
823
+ if (item.selected.length === 0 && custom === "") continue;
824
+ mapped.push({
825
+ id: question.id,
826
+ selected: [...item.selected],
827
+ ...custom === "" ? {} : { custom }
828
+ });
829
+ }
830
+ if (dropped > 0) console.warn("[question-timeout-protection] 有 " + String(dropped) + " 条草稿对不上本次提问的题目, 已丢弃");
831
+ if (mapped.length === 0) return {
832
+ pending: true,
833
+ callId,
834
+ message: TIMEOUT_PENDING_NOTICE
835
+ };
836
+ return {
837
+ pending: true,
838
+ callId,
839
+ message: TIMEOUT_PENDING_DRAFT_NOTICE,
840
+ draft: mapped
841
+ };
842
+ }
843
+ try {
844
+ const first = await Promise.race([wait.then((value) => ({
845
+ kind: "value",
846
+ value
847
+ }), (error) => ({
848
+ kind: "error",
849
+ error
850
+ })), expired.then((value) => ({
851
+ kind: "expired",
852
+ value
853
+ }))]);
854
+ if (first.kind === "error") throw first.error;
855
+ const result = first.value;
856
+ if (!("pending" in result)) return toAnswers(result);
857
+ if (infiniteEnabled && isInfiniteWait(exec.callId)) {
858
+ const settled = await wait;
859
+ if (!("pending" in settled)) return toAnswers(settled);
860
+ clearInfiniteWait(exec.callId);
861
+ return await pendingResult(settled.callId, false);
862
+ }
863
+ const settled = await Promise.race([wait.then((value) => ({
864
+ kind: "answer",
865
+ value
866
+ }), (error) => ({
867
+ kind: "error",
868
+ value: error
869
+ })), pendingResult(result.callId, true).then((value) => ({
870
+ kind: "pending",
871
+ value
872
+ }))]);
873
+ if (settled.kind === "error") throw settled.value;
874
+ if (settled.kind === "answer") {
875
+ if (!("pending" in settled.value)) return toAnswers(settled.value);
876
+ } else if (settled.value !== null) return settled.value;
877
+ const again = await wait;
878
+ if (!("pending" in again)) return toAnswers(again);
879
+ const settleId = again.callId;
880
+ const frozen = isInfiniteWait(settleId);
881
+ clearInfiniteWait(settleId);
882
+ if (frozen) forgetDraft(settleId);
883
+ return await pendingResult(settleId, false);
884
+ } finally {
885
+ waitController.abort();
886
+ linked.dispose();
887
+ clearInfiniteWait(exec.callId);
888
+ clearCallDeadline(exec.callId);
889
+ clearCallQuestions(exec.callId);
890
+ clearDraft(exec.callId);
891
+ forgetDraft(exec.callId);
892
+ markCallSettled(exec.callId);
893
+ if (timer !== void 0) clearTimeout(timer);
894
+ }
895
+ }
896
+ });
897
+ }
898
+ // src/question/service.ts
899
+ var QuestionTimeoutService = class {
900
+ ctx;
901
+ config;
902
+ perAgent = /* @__PURE__ */ new Map();
903
+ constructor(ctx, config) {
904
+ this.ctx = ctx;
905
+ this.config = config;
906
+ }
907
+ /** 建立 agent 创建监听,并为已存在的 agent 补齐工具注册 */
908
+ start() {
909
+ this.ctx.effect(() => {
910
+ const offCreated = this.ctx.on("agent/created", ({ agent }) => {
911
+ this.registerFor(agent);
912
+ }, { global: true });
913
+ const offDisposed = this.ctx.on("agent/disposed", ({ agent }) => {
914
+ this.forget(String(agent.id));
915
+ }, { global: true });
916
+ for (const agent of this.ctx.agents.list()) this.registerFor(agent);
917
+ return () => {
918
+ offCreated();
919
+ offDisposed();
920
+ this.dispose();
921
+ };
922
+ }, "question-timeout-protection: per-agent tool");
923
+ }
924
+ /** 释放插件持有的全部工具注册 */
925
+ dispose() {
926
+ for (const dispose of this.perAgent.values()) try {
927
+ dispose();
928
+ } catch {}
929
+ this.perAgent.clear();
930
+ }
931
+ /** 释放并忘掉一个 agent 的工具注册 */
932
+ forget(key) {
933
+ const dispose = this.perAgent.get(key);
934
+ if (dispose === void 0) return;
935
+ this.perAgent.delete(key);
936
+ try {
937
+ dispose();
938
+ } catch {}
939
+ }
940
+ /** 在一个 agent 的作用域注册同名提问工具, 同一 agent 只注册一次 */
941
+ registerFor(agent) {
942
+ const key = String(agent.id);
943
+ if (this.perAgent.has(key)) return;
944
+ try {
945
+ this.perAgent.set(key, agent.ctx.tools.register(createAskUserQuestionTool(this.ctx, this.config)));
946
+ } catch (error) {
947
+ this.ctx.logger.warn(`question-timeout-protection: failed to register the timed ask tool for agent ${key}: ${String(error)}`);
948
+ }
949
+ }
950
+ };
951
+ // src/locale-core.ts
952
+ function normalizeLocale(locale) {
953
+ const raw = locale.trim().toLowerCase().replace(/_/g, "-");
954
+ if (raw === "") return DEFAULT_LANGUAGE;
955
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(raw)) return DEFAULT_LANGUAGE;
956
+ const [language, ...rest] = raw.split("-");
957
+ const region = rest[0];
958
+ if (region !== void 0 && !/^[a-z0-9]+$/.test(region)) return DEFAULT_LANGUAGE;
959
+ if (language === "zh") return "zh-CN";
960
+ if (language === "en") return "en-US";
961
+ return region === void 0 ? language : language + "-" + region.toUpperCase();
962
+ }
963
+ // src/translation/index.ts
964
+ /** 当前文件所在目录(构建产物位于 dist/ 下) */
965
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
966
+ function parseTranslationSection(text) {
967
+ const table = {};
968
+ let inSection = false;
969
+ for (const raw of text.split(/\r?\n/)) {
970
+ const line = raw.trim();
971
+ if (line === "") continue;
972
+ const sectionMatch = line.match(/^\[([^\]]+)\]$/);
973
+ if (sectionMatch) {
974
+ inSection = sectionMatch[1] === "translation";
975
+ continue;
976
+ }
977
+ if (!inSection) continue;
978
+ if (line.startsWith(";") || line.startsWith("#")) continue;
979
+ const eq = line.indexOf("=");
980
+ if (eq <= 0) continue;
981
+ const key = line.slice(0, eq).trim();
982
+ const value = line.slice(eq + 1).trim();
983
+ if (key) table[key] = value;
984
+ }
985
+ return table;
986
+ }
987
+ /**
988
+ * 定位插件包根目录: 构建产物可能位于 dist/ 或被拆为 dist/ 下的分块,
989
+ * 依次尝试上溯一级与两级,取第一个存在翻译目录的候选。
990
+ */
991
+ function resolvePackageRoot() {
992
+ const candidates = [
993
+ join(MODULE_DIR, ".."),
994
+ join(MODULE_DIR, "..", ".."),
995
+ join(MODULE_DIR, "..", "..", "..")
996
+ ];
997
+ for (const candidate of candidates) if (existsSync(join(candidate, "src/translation"))) return candidate;
998
+ return join(MODULE_DIR, "..");
999
+ }
1000
+ /** 插件包根目录 */
1001
+ const PACKAGE_ROOT = resolvePackageRoot();
1002
+ const RETRY_INTERVAL_MS = 3e4;
1003
+ var TranslationManager = class {
1004
+ tables = /* @__PURE__ */ new Map();
1005
+ language = DEFAULT_LANGUAGE;
1006
+ warned = /* @__PURE__ */ new Set();
1007
+ failedAt = /* @__PURE__ */ new Map();
1008
+ /** 清空已加载的翻译表, 供测试或热更新后强制重读 */
1009
+ reload() {
1010
+ this.tables.clear();
1011
+ this.failedAt.clear();
1012
+ this.warned.clear();
1013
+ }
1014
+ /** 加载指定语言的翻译表; 读取失败时返回空表但不缓存, 便于修复后自动恢复 */
1015
+ load(locale) {
1016
+ const normalized = normalizeLocale(locale);
1017
+ const cached = this.tables.get(normalized);
1018
+ if (cached !== void 0) return cached;
1019
+ const failedAt = this.failedAt.get(normalized);
1020
+ if (failedAt !== void 0 && Date.now() - failedAt < RETRY_INTERVAL_MS) return {};
1021
+ const filePath = join(PACKAGE_ROOT, TRANSLATION_DIR, `${normalized}.ini`);
1022
+ try {
1023
+ const table = parseTranslationSection(readFileSync(filePath, "utf-8"));
1024
+ if (Object.keys(table).length === 0) {
1025
+ this.failedAt.set(normalized, Date.now());
1026
+ if (!this.warned.has(normalized)) {
1027
+ this.warned.add(normalized);
1028
+ console.warn("[question-timeout-protection] 翻译文件没有可用条目, 未命中时回退到兜底语言 zh-CN:", filePath);
1029
+ }
1030
+ return {};
1031
+ }
1032
+ this.tables.set(normalized, table);
1033
+ this.failedAt.delete(normalized);
1034
+ return table;
1035
+ } catch (error) {
1036
+ this.failedAt.set(normalized, Date.now());
1037
+ if (!this.warned.has(normalized)) {
1038
+ this.warned.add(normalized);
1039
+ console.warn("[question-timeout-protection] 翻译文件读取失败, 未命中时回退到兜底语言 zh-CN:", error instanceof Error ? error.message : String(error));
1040
+ }
1041
+ return {};
1042
+ }
1043
+ }
1044
+ /** 切换当前语言 */
1045
+ setLanguage(locale) {
1046
+ this.language = normalizeLocale(locale);
1047
+ this.load(this.language);
1048
+ }
1049
+ /** 取翻译文本,未命中回退默认语言,仍未命中返回键名 */
1050
+ translate(key) {
1051
+ const current = this.load(this.language);
1052
+ const fallback = this.load(FALLBACK_LANGUAGE);
1053
+ if (Object.prototype.hasOwnProperty.call(current, key)) return current[key];
1054
+ if (Object.prototype.hasOwnProperty.call(fallback, key)) return fallback[key];
1055
+ return key;
1056
+ }
1057
+ };
1058
+ /** 翻译文本快捷方法(使用默认实例) */
1059
+ const translation = new TranslationManager();
1060
+ // src/index.ts
1061
+ const name = PLUGIN_NAME;
1062
+ const inject = [
1063
+ "tools",
1064
+ "userQuestions",
1065
+ "agents"
1066
+ ];
1067
+ /** 插件装配入口 */
1068
+ function apply(ctx, config) {
1069
+ const service = new QuestionTimeoutService(ctx, config);
1070
+ service.start();
1071
+ let syncStarted = false;
1072
+ ctx.inject(["webServer"], (scoped) => {
1073
+ const holder = scoped ?? ctx;
1074
+ const webServer = holder.webServer;
1075
+ if (webServer === void 0) return;
1076
+ try {
1077
+ const off = registerQuestionSyncRoute(webServer);
1078
+ syncStarted = true;
1079
+ holder.effect?.(() => off);
1080
+ } catch (error) {
1081
+ console.warn("[question-timeout-protection] 状态同步路由注册失败, 「无限等待」与草稿上报在本部署不可用", error);
1082
+ }
1083
+ });
1084
+ const syncProbe = setTimeout(() => {
1085
+ if (syncStarted) return;
1086
+ console.warn("[question-timeout-protection] 未检测到宿主 HTTP 服务, 状态同步通道未启动, 「无限等待」与草稿上报在本部署不可用");
1087
+ }, 5e3);
1088
+ syncProbe.unref?.();
1089
+ ctx.effect(() => () => {
1090
+ clearTimeout(syncProbe);
1091
+ service.dispose();
1092
+ stopQuestionSync();
1093
+ });
1094
+ }
1095
+ export { Config, QuestionTimeoutService, TranslationManager, apply, inject, name, translation };