dsh-better-ask-user 0.3.6 → 0.3.7-alpha.1

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.
Files changed (45) hide show
  1. package/README.md +7 -7
  2. package/lib/ask-tool.d.ts +15 -0
  3. package/lib/ask-tool.js +161 -0
  4. package/lib/ask-tool.js.map +1 -0
  5. package/lib/client.js +1 -0
  6. package/lib/config.d.ts +29 -0
  7. package/lib/config.js +48 -0
  8. package/lib/config.js.map +1 -0
  9. package/lib/default-answer.d.ts +22 -0
  10. package/lib/default-answer.js +38 -0
  11. package/lib/default-answer.js.map +1 -0
  12. package/lib/index.d.ts +7 -0
  13. package/lib/index.js +48 -0
  14. package/lib/index.js.map +1 -0
  15. package/lib/ptc.d.ts +3 -0
  16. package/lib/ptc.js +13 -0
  17. package/lib/ptc.js.map +1 -0
  18. package/lib/settings.d.ts +36 -0
  19. package/lib/settings.js +81 -0
  20. package/lib/settings.js.map +1 -0
  21. package/package.json +49 -19
  22. package/src/ask-tool.js +0 -165
  23. package/src/client/AskHistoryRow.module.css +0 -26
  24. package/src/client/AskHistoryRow.tsx +0 -173
  25. package/src/client/PlanReviewPanel.module.css +0 -255
  26. package/src/client/PlanReviewPanel.tsx +0 -147
  27. package/src/client/QuestionComposer.module.css +0 -494
  28. package/src/client/QuestionComposer.tsx +0 -656
  29. package/src/client/QuestionReplyView.module.css +0 -100
  30. package/src/client/QuestionReplyView.tsx +0 -124
  31. package/src/client/QuestionWaitBar.module.css +0 -41
  32. package/src/client/QuestionWaitBar.tsx +0 -41
  33. package/src/client/contract/slots.ts +0 -650
  34. package/src/client/draft-store.ts +0 -64
  35. package/src/client/index.ts +0 -497
  36. package/src/client/locales.ts +0 -100
  37. package/src/client/question-reply.ts +0 -187
  38. package/src/client/settings-locales.ts +0 -79
  39. package/src/client/settings.module.css +0 -122
  40. package/src/client/settings.tsx +0 -336
  41. package/src/config.js +0 -54
  42. package/src/default-answer.js +0 -39
  43. package/src/index.js +0 -50
  44. package/src/ptc.js +0 -11
  45. package/src/settings.js +0 -81
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  <p align="center">
13
13
  <a href="https://www.npmjs.com/package/dsh-better-ask-user"><img src="https://img.shields.io/npm/v/dsh-better-ask-user.svg" alt="npm 版本"></a>
14
14
  <a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/github/license/omdsh-dev/dsh-better-ask-user?color=blue"></a>
15
- <a href="package.json"><img alt="DSH 0.2.2-rc.3" src="https://img.shields.io/badge/DSH-0.2.2--rc.3-4B32C3"></a>
15
+ <a href="package.json"><img alt="DSH 0.2.3-alpha.2" src="https://img.shields.io/badge/DSH-0.2.3--alpha.2-4B32C3"></a>
16
16
  <a href="https://github.com/omdsh-dev/dsh-better-dsh"><img alt="Part of Better DSH" src="https://img.shields.io/badge/part%20of-dsh--better--dsh-2F80B7"></a>
17
17
  </p>
18
18
 
@@ -42,7 +42,7 @@
42
42
 
43
43
  ```sh
44
44
  # 只安装这个插件
45
- dsh plugin --profile <profile> add dsh-better-ask-user@0.3.6 dsh-better-ptc@0.2.2
45
+ dsh plugin --profile <profile> add dsh-better-ask-user@0.3.7-alpha.1 dsh-better-ptc@0.2.3-alpha.1
46
46
 
47
47
  # 或安装 Better DSH(会自动带上所有独立插件)
48
48
  dsh plugin --profile <profile> add dsh-better-dsh@0.11.7
@@ -63,7 +63,7 @@ dsh plugin --profile <profile> add dsh-better-dsh@0.11.7
63
63
  | 稳定行 id | `dsh-better-ask-user` |
64
64
  | 入口 / 工具 | `ask_user_question` · 问题卡片 / 等待时间线 · 提问设置页 |
65
65
  | 设置 | 等待时长、输入续期、普通 / Goal 超时行为 |
66
- | npm 包 | `dsh-better-ask-user@0.3.6` |
66
+ | npm 包 | `dsh-better-ask-user@0.3.7-alpha.1` |
67
67
  | 仓库 | https://github.com/omdsh-dev/dsh-better-ask-user |
68
68
 
69
69
  ## 设置
@@ -83,12 +83,12 @@ dsh plugin --profile <profile> add dsh-better-dsh@0.11.7
83
83
  ## 开发
84
84
 
85
85
  ```sh
86
- npm test # 单元 / 组件测试
87
- npm run smoke # 如仓库提供运行时冒烟
86
+ npm install
87
+ npm run build # tsc 生成宿主 lib/,esbuild 生成浏览器 closure
88
+ npm run typecheck # 宿主 + 浏览器两份 tsconfig
89
+ npm test # pretest 会先构建
88
90
  ```
89
91
 
90
- 实现与测试说明见 [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)。
91
-
92
92
  ## 许可
93
93
 
94
94
  [Apache License 2.0](LICENSE)。
@@ -0,0 +1,15 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
3
+ import type { AskConfig } from './config.js';
4
+ /** Model-visible notice for the native pending result. */
5
+ export declare const PENDING_QUESTION_NOTICE = "No answer batch arrived before the timeout. This is pending, not a skipped answer. Continue useful independent work. The user can still answer; their reply will be a user message identified as answer_to_pending_question with this callId and the original questions. Do not treat this as permission.";
6
+ /** Model-visible warning for a host auto-selected default batch. */
7
+ export declare const AUTO_SELECTED_WARNING = "These answers were auto-selected by the host timeout behavior, not submitted by the user. Do not treat them as user confirmation.";
8
+ /**
9
+ * Build the ask_user_question shadow from the currently registered base tool.
10
+ * @param ctx - root host context with userQuestions and optional goals.
11
+ * @param base - existing official ask_user_question definition.
12
+ * @param readConfig - live config reader.
13
+ * @returns a ToolDefinition with the official contract and the plugin wait.
14
+ */
15
+ export declare function createBetterAskTool(ctx: Context, base: ToolDefinition, readConfig: () => AskConfig): ToolDefinition;
@@ -0,0 +1,161 @@
1
+ /** ask_user_question scope shadow: official contract plus the plugin-managed wait. */
2
+ import { ToolArgsError, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools';
3
+ import { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions';
4
+ import { buildDefaultAnswer } from './default-answer.js';
5
+ /** Model-visible notice for the native pending result. */
6
+ export const PENDING_QUESTION_NOTICE = 'No answer batch arrived before the timeout. This is pending, not a skipped answer. Continue useful independent work. The user can still answer; their reply will be a user message identified as answer_to_pending_question with this callId and the original questions. Do not treat this as permission.';
7
+ /** Model-visible warning for a host auto-selected default batch. */
8
+ export const AUTO_SELECTED_WARNING = 'These answers were auto-selected by the host timeout behavior, not submitted by the user. Do not treat them as user confirmation.';
9
+ function questionRequest(questions, exec) {
10
+ return {
11
+ questions: questions.map(question => ({
12
+ id: question.id,
13
+ question: question.question,
14
+ ...(question.header !== undefined ? { header: question.header } : {}),
15
+ ...(question.detail !== undefined ? { detail: question.detail } : {}),
16
+ ...(question.options !== undefined ? {
17
+ options: question.options.map(option => ({ ...option })),
18
+ } : {}),
19
+ ...(question.multi_select !== undefined ? { multiSelect: question.multi_select } : {}),
20
+ })),
21
+ ...(exec.agent !== undefined ? { agent: exec.agent } : {}),
22
+ signal: exec.signal,
23
+ };
24
+ }
25
+ function validateQuestionIds(questions) {
26
+ const ids = new Set();
27
+ for (const question of questions) {
28
+ if (ids.has(question.id))
29
+ throw new Error('question id ' + JSON.stringify(question.id) + ' must be unique within this call');
30
+ ids.add(question.id);
31
+ }
32
+ }
33
+ function answerResult(result) {
34
+ return {
35
+ answers: result.answers.map(answer => ({
36
+ id: answer.id,
37
+ selected: [...answer.selected],
38
+ ...(answer.custom !== undefined ? { custom: answer.custom } : {}),
39
+ })),
40
+ ...(result.autoSelected === true ? { autoSelected: true, warning: AUTO_SELECTED_WARNING } : {}),
41
+ };
42
+ }
43
+ /** Add detail and the next host marker used to replay pending questions. */
44
+ function parametersWithDetail(parameters) {
45
+ if (parameters === undefined)
46
+ return parameters;
47
+ const next = structuredClone(parameters);
48
+ // DSH classifies logged ask calls by this schema key, not by askTimed usage.
49
+ next.properties[TIMED_WAIT_PARAMETER] = {
50
+ type: 'integer',
51
+ description: 'Host continuation marker; omit. The plugin setting, not this argument, controls foreground wait duration.',
52
+ };
53
+ const properties = next?.properties?.questions?.items?.properties;
54
+ if (properties !== undefined && properties.detail === undefined) {
55
+ properties.detail = {
56
+ type: 'string',
57
+ description: 'Optional longer detail or context rendered as sanitized markdown below the question.',
58
+ };
59
+ }
60
+ return next;
61
+ }
62
+ /** Allow the additive auto-selected warning fields on the normal answer branch. */
63
+ function extendAutoSelectedSchema(schema) {
64
+ const branches = Array.isArray(schema?.oneOf) ? schema.oneOf : [schema];
65
+ for (const branch of branches) {
66
+ const properties = branch?.properties;
67
+ if (properties?.answers === undefined)
68
+ continue;
69
+ if (properties.autoSelected === undefined) {
70
+ properties.autoSelected = {
71
+ type: 'boolean',
72
+ description: 'True when the host auto-selected the default batch after the timeout; not a user answer.',
73
+ };
74
+ }
75
+ if (properties.warning === undefined) {
76
+ properties.warning = { type: 'string', description: 'Model-visible warning for an auto-selected batch.' };
77
+ }
78
+ }
79
+ return schema;
80
+ }
81
+ /** The timed path can return the official pending shape; keep it valid. */
82
+ function outputWithPending(base) {
83
+ const output = { ...base.output };
84
+ const schema = extendAutoSelectedSchema(structuredClone(base.output.schema));
85
+ if (Array.isArray(schema?.oneOf) && schema.oneOf.some(branch => branch?.properties?.pending !== undefined)) {
86
+ output.schema = schema;
87
+ return output;
88
+ }
89
+ output.schema = {
90
+ oneOf: [
91
+ schema,
92
+ {
93
+ type: 'object',
94
+ additionalProperties: false,
95
+ properties: {
96
+ pending: { type: 'boolean' },
97
+ callId: { type: 'string' },
98
+ message: { type: 'string' },
99
+ },
100
+ required: ['pending', 'callId', 'message'],
101
+ },
102
+ ],
103
+ };
104
+ return output;
105
+ }
106
+ /**
107
+ * Build the ask_user_question shadow from the currently registered base tool.
108
+ * @param ctx - root host context with userQuestions and optional goals.
109
+ * @param base - existing official ask_user_question definition.
110
+ * @param readConfig - live config reader.
111
+ * @returns a ToolDefinition with the official contract and the plugin wait.
112
+ */
113
+ export function createBetterAskTool(ctx, base, readConfig) {
114
+ const output = outputWithPending(base);
115
+ const parameters = parametersWithDetail(base.parameters);
116
+ const execute = async (input, exec) => {
117
+ const violations = validateJsonSchemaValue(parameters, input, '');
118
+ if (violations.length > 0)
119
+ throw new ToolArgsError(violations);
120
+ // The official input schema has validated this model-facing question shape.
121
+ const args = input;
122
+ validateQuestionIds(args.questions);
123
+ const userQuestions = ctx.get('userQuestions');
124
+ if (userQuestions === undefined)
125
+ throw new Error('ask_user_question requires the userQuestions service');
126
+ const config = readConfig();
127
+ const goal = exec.agent === undefined ? undefined : ctx.get('goals')?.get?.(exec.agent);
128
+ const goalActive = goal?.phase === 'active' && goal.activation === 'armed';
129
+ const mode = goalActive ? config.goalTimeoutBehavior : config.timeoutBehavior;
130
+ const seconds = config.questionTimeoutSeconds;
131
+ const questions = questionRequest(args.questions, exec);
132
+ const defaultAnswer = mode === 'default' && seconds !== -1
133
+ ? answerResult(buildDefaultAnswer(args.questions))
134
+ : undefined;
135
+ if (seconds === -1) {
136
+ const result = await userQuestions.ask({ ...questions, wait: { callId: exec.callId } });
137
+ return answerResult(result);
138
+ }
139
+ if (exec.agent === undefined)
140
+ throw new Error('timed questions require a live agent');
141
+ const waitMs = seconds * 1000;
142
+ const request = {
143
+ ...questions,
144
+ agent: exec.agent,
145
+ better: {
146
+ waitMs,
147
+ timeoutMode: mode,
148
+ ...(defaultAnswer !== undefined ? { defaultAnswer } : {}),
149
+ },
150
+ };
151
+ const result = await userQuestions.askTimed(request, exec.callId, waitMs);
152
+ if ('pending' in result) {
153
+ if (mode === 'default' && defaultAnswer !== undefined)
154
+ return answerResult(defaultAnswer);
155
+ return { ...result, message: PENDING_QUESTION_NOTICE };
156
+ }
157
+ return answerResult(result);
158
+ };
159
+ return { ...base, parameters, output, execute };
160
+ }
161
+ //# sourceMappingURL=ask-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ask-tool.js","sourceRoot":"","sources":["../src/ask-tool.ts"],"names":[],"mappings":"AAAA,sFAAsF;AACtF,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAA;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAA;A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AAK,CAAC,sCAAsC,CAAC,CAAA;QAErF,MAAM,MAAM,GAAG,OAAO,GAAG,IAAI,CAAA;QAC7B,MAAM,OAAO,GAAwD;YACnE,GAAG,SAAS;YACZ,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE;gBACN,MAAM;gBACN,WAAW,EAAE,IAAI;gBACjB,GAAG,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC1D;SACF,CAAA;QACD,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QACzE,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;YACxB,IAAI,IAAI,KAAK,SAAS,IAAI,aAAa,KAAK,SAAS;gBAAE,OAAO,YAAY,CAAC,aAAa,CAAC,CAAA;YACzF,OAAO,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,uBAAuB,EAAE,CAAA;QACxD,CAAC;QACD,OAAO,YAAY,CAAC,MAAM,CAAC,CAAA;IAC7B,CAAC,CAAA;IAED,OAAO,EAAE,GAAG,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,CAAA;AACjD,CAAC","sourcesContent":["/** ask_user_question scope shadow: official contract plus the plugin-managed wait. */\nimport { ToolArgsError, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools'\nimport { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { JsonSchemaNode, ToolDefinition, ToolRunContext } from '@deepseek-ai/dsh-tools'\nimport type { AskUserQuestionAnswer, AskUserQuestionRequest } from '@deepseek-ai/dsh-user-questions'\nimport type { AskConfig } from './config.js'\nimport { buildDefaultAnswer } from './default-answer.js'\nimport type { ModelQuestion } from './default-answer.js'\n\n/** Model-visible notice for the native pending result. */\nexport const PENDING_QUESTION_NOTICE = 'No answer batch arrived before the timeout. This is pending, not a skipped answer. Continue useful independent work. The user can still answer; their reply will be a user message identified as answer_to_pending_question with this callId and the original questions. Do not treat this as permission.'\n\n/** Model-visible warning for a host auto-selected default batch. */\nexport const AUTO_SELECTED_WARNING = 'These answers were auto-selected by the host timeout behavior, not submitted by the user. Do not treat them as user confirmation.'\n\nfunction questionRequest(questions: ModelQuestion[], exec: ToolRunContext): AskUserQuestionRequest {\n return {\n questions: questions.map(question => ({\n id: question.id,\n question: question.question,\n ...(question.header !== undefined ? { header: question.header } : {}),\n ...(question.detail !== undefined ? { detail: question.detail } : {}),\n ...(question.options !== undefined ? {\n options: question.options.map(option => ({ ...option })),\n } : {}),\n ...(question.multi_select !== undefined ? { multiSelect: question.multi_select } : {}),\n })),\n ...(exec.agent !== undefined ? { agent: exec.agent } : {}),\n signal: exec.signal,\n }\n}\n\nfunction validateQuestionIds(questions: ModelQuestion[]) {\n const ids = new Set()\n for (const question of questions) {\n if (ids.has(question.id)) throw new Error('question id ' + JSON.stringify(question.id) + ' must be unique within this call')\n ids.add(question.id)\n }\n}\n\nfunction answerResult(result: AskUserQuestionAnswer & { autoSelected?: boolean }) {\n return {\n answers: result.answers.map(answer => ({\n id: answer.id,\n selected: [...answer.selected],\n ...(answer.custom !== undefined ? { custom: answer.custom } : {}),\n })),\n ...(result.autoSelected === true ? { autoSelected: true, warning: AUTO_SELECTED_WARNING } : {}),\n }\n}\n\n/** Add detail and the next host marker used to replay pending questions. */\nfunction parametersWithDetail(parameters: ToolDefinition['parameters']) {\n if (parameters === undefined) return parameters\n const next = structuredClone(parameters) as JsonSchemaNode & typeof parameters\n // DSH classifies logged ask calls by this schema key, not by askTimed usage.\n next.properties![TIMED_WAIT_PARAMETER] = {\n type: 'integer',\n description: 'Host continuation marker; omit. The plugin setting, not this argument, controls foreground wait duration.',\n }\n const properties = next?.properties?.questions?.items?.properties\n if (properties !== undefined && properties.detail === undefined) {\n properties.detail = {\n type: 'string',\n description: 'Optional longer detail or context rendered as sanitized markdown below the question.',\n }\n }\n return next\n}\n\n/** Allow the additive auto-selected warning fields on the normal answer branch. */\nfunction extendAutoSelectedSchema(schema: JsonSchemaNode) {\n const branches = Array.isArray(schema?.oneOf) ? schema.oneOf : [schema]\n for (const branch of branches) {\n const properties = branch?.properties\n if (properties?.answers === undefined) continue\n if (properties.autoSelected === undefined) {\n properties.autoSelected = {\n type: 'boolean',\n description: 'True when the host auto-selected the default batch after the timeout; not a user answer.',\n }\n }\n if (properties.warning === undefined) {\n properties.warning = { type: 'string', description: 'Model-visible warning for an auto-selected batch.' }\n }\n }\n return schema\n}\n\n/** The timed path can return the official pending shape; keep it valid. */\nfunction outputWithPending(base: ToolDefinition) {\n const output = { ...base.output }\n const schema = extendAutoSelectedSchema(structuredClone(base.output.schema))\n if (Array.isArray(schema?.oneOf) && schema.oneOf.some(branch => branch?.properties?.pending !== undefined)) {\n output.schema = schema\n return output\n }\n output.schema = {\n oneOf: [\n schema,\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n pending: { type: 'boolean' },\n callId: { type: 'string' },\n message: { type: 'string' },\n },\n required: ['pending', 'callId', 'message'],\n },\n ],\n }\n return output\n}\n\n/**\n * Build the ask_user_question shadow from the currently registered base tool.\n * @param ctx - root host context with userQuestions and optional goals.\n * @param base - existing official ask_user_question definition.\n * @param readConfig - live config reader.\n * @returns a ToolDefinition with the official contract and the plugin wait.\n */\nexport function createBetterAskTool(ctx: Context, base: ToolDefinition, readConfig: () => AskConfig): ToolDefinition {\n const output = outputWithPending(base)\n const parameters = parametersWithDetail(base.parameters)\n\n const execute = async (input: unknown, exec: ToolRunContext) => {\n const violations = validateJsonSchemaValue(parameters, input, '')\n if (violations.length > 0) throw new ToolArgsError(violations)\n // The official input schema has validated this model-facing question shape.\n const args = input as { questions: ModelQuestion[] }\n validateQuestionIds(args.questions)\n\n const userQuestions = ctx.get('userQuestions')\n if (userQuestions === undefined) throw new Error('ask_user_question requires the userQuestions service')\n\n const config = readConfig()\n const goal = exec.agent === undefined ? undefined : ctx.get('goals')?.get?.(exec.agent)\n const goalActive = goal?.phase === 'active' && goal.activation === 'armed'\n const mode = goalActive ? config.goalTimeoutBehavior : config.timeoutBehavior\n const seconds = config.questionTimeoutSeconds\n const questions = questionRequest(args.questions, exec)\n const defaultAnswer = mode === 'default' && seconds !== -1\n ? answerResult(buildDefaultAnswer(args.questions))\n : undefined\n\n if (seconds === -1) {\n const result = await userQuestions.ask({ ...questions, wait: { callId: exec.callId } })\n return answerResult(result)\n }\n if (exec.agent === undefined) throw new Error('timed questions require a live agent')\n\n const waitMs = seconds * 1000\n const request: Parameters<Context['userQuestions']['askTimed']>[0] = {\n ...questions,\n agent: exec.agent,\n better: {\n waitMs,\n timeoutMode: mode,\n ...(defaultAnswer !== undefined ? { defaultAnswer } : {}),\n },\n }\n const result = await userQuestions.askTimed(request, exec.callId, waitMs)\n if ('pending' in result) {\n if (mode === 'default' && defaultAnswer !== undefined) return answerResult(defaultAnswer)\n return { ...result, message: PENDING_QUESTION_NOTICE }\n }\n return answerResult(result)\n }\n\n return { ...base, parameters, output, execute }\n}"]}
package/lib/client.js CHANGED
@@ -3,6 +3,7 @@ window.__ModuleLoader__.load({
3
3
  factory: (require) => {
4
4
  var module = { exports: {} };
5
5
  var exports = module.exports;
6
+ "use strict";
6
7
  var __defProp = Object.defineProperty;
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
9
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -0,0 +1,29 @@
1
+ /** Formal row Config and live-value normalization. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ /** Largest question wait a native platform timer can represent, in seconds. */
4
+ export declare const MAX_QUESTION_TIMEOUT_SECONDS = 2147483;
5
+ /** Plain defaults mirrored by the client form. */
6
+ export declare const DEFAULTS: Readonly<{
7
+ questionTimeoutSeconds: 120;
8
+ timeoutBehavior: "native";
9
+ goalTimeoutBehavior: "native";
10
+ }>;
11
+ /** The plugin row's formal configuration; every field hot-updates. */
12
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
13
+ questionTimeoutSeconds: z<number, number, "volatile-defined">;
14
+ timeoutBehavior: z<"native" | "default", "native" | "default", "volatile-defined">;
15
+ goalTimeoutBehavior: z<"native" | "default", "native" | "default", "volatile-defined">;
16
+ }>>, Schemastery.ObjectT<NoInfer<{
17
+ questionTimeoutSeconds: z<number, number, "volatile-defined">;
18
+ timeoutBehavior: z<"native" | "default", "native" | "default", "volatile-defined">;
19
+ goalTimeoutBehavior: z<"native" | "default", "native" | "default", "volatile-defined">;
20
+ }>>, "plain">;
21
+ export interface AskConfig {
22
+ questionTimeoutSeconds: number;
23
+ timeoutBehavior: 'native' | 'default';
24
+ goalTimeoutBehavior: 'native' | 'default';
25
+ }
26
+ /** Normalize arbitrary live config to the exact default shape; never throw. */
27
+ export declare function normalizeConfig(value: unknown): AskConfig;
28
+ /** Read the current live config. */
29
+ export declare function readConfig(value: unknown): AskConfig;
package/lib/config.js ADDED
@@ -0,0 +1,48 @@
1
+ /** Formal row Config and live-value normalization. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ /** Largest question wait a native platform timer can represent, in seconds. */
4
+ export const MAX_QUESTION_TIMEOUT_SECONDS = 2147483;
5
+ /** Plain defaults mirrored by the client form. */
6
+ export const DEFAULTS = Object.freeze({
7
+ questionTimeoutSeconds: 120,
8
+ timeoutBehavior: 'native',
9
+ goalTimeoutBehavior: 'native',
10
+ });
11
+ const QuestionTimeout = z
12
+ .union([z.const(-1), z.natural().min(1).max(MAX_QUESTION_TIMEOUT_SECONDS)])
13
+ .default(DEFAULTS.questionTimeoutSeconds);
14
+ /** The plugin row's formal configuration; every field hot-updates. */
15
+ export const Config = z.object({
16
+ questionTimeoutSeconds: QuestionTimeout.volatile(),
17
+ timeoutBehavior: z.union(['native', 'default']).default(DEFAULTS.timeoutBehavior).volatile(),
18
+ goalTimeoutBehavior: z.union(['native', 'default']).default(DEFAULTS.goalTimeoutBehavior).volatile(),
19
+ });
20
+ function primitive(value) {
21
+ return value !== null && typeof value === 'object' && typeof value.get === 'function'
22
+ ? value.get()
23
+ : value;
24
+ }
25
+ /** Normalize arbitrary live config to the exact default shape; never throw. */
26
+ export function normalizeConfig(value) {
27
+ const source = value !== null && typeof value === 'object' ? value : {};
28
+ const seconds = primitive(source.questionTimeoutSeconds);
29
+ const behavior = primitive(source.timeoutBehavior);
30
+ const goalBehavior = primitive(source.goalTimeoutBehavior);
31
+ return {
32
+ questionTimeoutSeconds: seconds === -1
33
+ || (typeof seconds === 'number' && Number.isInteger(seconds) && seconds >= 1 && seconds <= MAX_QUESTION_TIMEOUT_SECONDS)
34
+ ? seconds
35
+ : DEFAULTS.questionTimeoutSeconds,
36
+ timeoutBehavior: behavior === 'native' || behavior === 'default'
37
+ ? behavior
38
+ : DEFAULTS.timeoutBehavior,
39
+ goalTimeoutBehavior: goalBehavior === 'native' || goalBehavior === 'default'
40
+ ? goalBehavior
41
+ : DEFAULTS.goalTimeoutBehavior,
42
+ };
43
+ }
44
+ /** Read the current live config. */
45
+ export function readConfig(value) {
46
+ return normalizeConfig(value);
47
+ }
48
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAExC,+EAA+E;AAC/E,MAAM,CAAC,MAAM,4BAA4B,GAAG,OAAO,CAAA;AAEnD,kDAAkD;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,sBAAsB,EAAE,GAAG;IAC3B,eAAe,EAAE,QAAQ;IACzB,mBAAmB,EAAE,QAAQ;CAC9B,CAAC,CAAA;AAEF,MAAM,eAAe,GAAG,CAAC;KACtB,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,GAA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AAO,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,IAAI,4BAA4B,CAAC;YACxH,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,QAAQ,CAAC,sBAAsB;QACnC,eAAe,EAAE,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,SAAS;YAC9D,CAAC,CAAC,QAAQ;YACV,CAAC,CAAC,QAAQ,CAAC,eAAe;QAC5B,mBAAmB,EAAE,YAAY,KAAK,QAAQ,IAAI,YAAY,KAAK,SAAS;YAC1E,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,QAAQ,CAAC,mBAAmB;KACjC,CAAA;AACH,CAAC;AAED,oCAAoC;AACpC,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,eAAe,CAAC,KAAK,CAAC,CAAA;AAC/B,CAAC","sourcesContent":["/** Formal row Config and live-value normalization. */\nimport z from '@deepseek-ai/schemastery'\n\n/** Largest question wait a native platform timer can represent, in seconds. */\nexport const MAX_QUESTION_TIMEOUT_SECONDS = 2147483\n\n/** Plain defaults mirrored by the client form. */\nexport const DEFAULTS = Object.freeze({\n questionTimeoutSeconds: 120,\n timeoutBehavior: 'native',\n goalTimeoutBehavior: 'native',\n})\n\nconst QuestionTimeout = z\n .union([z.const(-1), z.natural().min(1).max(MAX_QUESTION_TIMEOUT_SECONDS)])\n .default(DEFAULTS.questionTimeoutSeconds)\n\n/** The plugin row's formal configuration; every field hot-updates. */\nexport const Config = z.object({\n questionTimeoutSeconds: QuestionTimeout.volatile(),\n timeoutBehavior: z.union(['native', 'default']).default(DEFAULTS.timeoutBehavior).volatile(),\n goalTimeoutBehavior: z.union(['native', 'default']).default(DEFAULTS.goalTimeoutBehavior).volatile(),\n})\n\nexport interface AskConfig {\n questionTimeoutSeconds: number\n timeoutBehavior: 'native' | 'default'\n goalTimeoutBehavior: 'native' | 'default'\n}\n\nfunction primitive(value: unknown): unknown {\n return value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function'\n ? (value as { get(): unknown }).get()\n : value\n}\n\n/** Normalize arbitrary live config to the exact default shape; never throw. */\nexport function normalizeConfig(value: unknown): AskConfig {\n const source = value !== null && typeof value === 'object' ? value as Record<string, unknown> : {}\n const seconds = primitive(source.questionTimeoutSeconds)\n const behavior = primitive(source.timeoutBehavior)\n const goalBehavior = primitive(source.goalTimeoutBehavior)\n return {\n questionTimeoutSeconds: seconds === -1\n || (typeof seconds === 'number' && Number.isInteger(seconds) && seconds >= 1 && seconds <= MAX_QUESTION_TIMEOUT_SECONDS)\n ? seconds\n : DEFAULTS.questionTimeoutSeconds,\n timeoutBehavior: behavior === 'native' || behavior === 'default'\n ? behavior\n : DEFAULTS.timeoutBehavior,\n goalTimeoutBehavior: goalBehavior === 'native' || goalBehavior === 'default'\n ? goalBehavior\n : DEFAULTS.goalTimeoutBehavior,\n }\n}\n\n/** Read the current live config. */\nexport function readConfig(value: unknown): AskConfig {\n return normalizeConfig(value)\n}\n"]}
@@ -0,0 +1,22 @@
1
+ /** Host-authored default answer for the configured timeout behavior. */
2
+ import type { AskUserQuestionAnswer, AskUserQuestionItem } from '@deepseek-ai/dsh-user-questions';
3
+ export type ModelQuestion = Omit<AskUserQuestionItem, 'multiSelect' | 'intent'> & {
4
+ multi_select?: boolean;
5
+ };
6
+ export type DefaultQuestion = Pick<ModelQuestion, 'id' | 'options' | 'multi_select'>;
7
+ /** Whether one option label carries the conventional recommendation suffix. */
8
+ export declare function isRecommended(label: unknown): boolean;
9
+ /**
10
+ * Build the default answer for a question batch.
11
+ *
12
+ * Single-select always picks the first option. Multi-select picks every
13
+ * recommended option; when none is recommended it picks the first option.
14
+ * A question with no options is skipped with an empty selected list. The
15
+ * returned object is marked autoSelected so the model can tell it apart from
16
+ * a human answer.
17
+ * @param questions - model-facing question items (raw args shape).
18
+ * @returns an answer batch with autoSelected true.
19
+ */
20
+ export declare function buildDefaultAnswer(questions: readonly DefaultQuestion[]): AskUserQuestionAnswer & {
21
+ autoSelected: true;
22
+ };
@@ -0,0 +1,38 @@
1
+ const RECOMMENDED_SUFFIX = /\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/i;
2
+ /** Whether one option label carries the conventional recommendation suffix. */
3
+ export function isRecommended(label) {
4
+ return typeof label === 'string' && RECOMMENDED_SUFFIX.test(label);
5
+ }
6
+ /**
7
+ * Build the default answer for a question batch.
8
+ *
9
+ * Single-select always picks the first option. Multi-select picks every
10
+ * recommended option; when none is recommended it picks the first option.
11
+ * A question with no options is skipped with an empty selected list. The
12
+ * returned object is marked autoSelected so the model can tell it apart from
13
+ * a human answer.
14
+ * @param questions - model-facing question items (raw args shape).
15
+ * @returns an answer batch with autoSelected true.
16
+ */
17
+ export function buildDefaultAnswer(questions) {
18
+ const answers = [];
19
+ for (const question of questions) {
20
+ const options = Array.isArray(question.options) ? question.options : [];
21
+ if (options.length === 0) {
22
+ answers.push({ id: question.id, selected: [] });
23
+ continue;
24
+ }
25
+ let selected;
26
+ if (question.multi_select === true) {
27
+ selected = options.filter(option => isRecommended(option.label)).map(option => option.label);
28
+ if (selected.length === 0)
29
+ selected = [options[0].label];
30
+ }
31
+ else {
32
+ selected = [options[0].label];
33
+ }
34
+ answers.push({ id: question.id, selected: [...new Set(selected)] });
35
+ }
36
+ return { answers, autoSelected: true };
37
+ }
38
+ //# sourceMappingURL=default-answer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-answer.js","sourceRoot":"","sources":["../src/default-answer.ts"],"names":[],"mappings":"AAMA,MAAM,kBAAkB,GAAG,yDAAyD,CAAA;AAEpF,+EAA+E;AAC/E,MAAM,UAAU,aAAa,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;AACpE,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAqC;IACtE,MAAM,OAAO,GAAqC,EAAE,CAAA;IACpD,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QACjC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAA;QACvE,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAA;YAC/C,SAAQ;QACV,CAAC;QACD,IAAI,QAAQ,CAAA;QACZ,IAAI,QAAQ,CAAC,YAAY,KAAK,IAAI,EAAE,CAAC;YACnC,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAC5F,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;gBAAE,QAAQ,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;QAC1D,CAAC;aAAM,CAAC;YACN,QAAQ,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;QAC/B,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAA;IACrE,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,CAAA;AACxC,CAAC","sourcesContent":["/** Host-authored default answer for the configured timeout behavior. */\nimport type { AskUserQuestionAnswer, AskUserQuestionItem } from '@deepseek-ai/dsh-user-questions'\n\nexport type ModelQuestion = Omit<AskUserQuestionItem, 'multiSelect' | 'intent'> & { multi_select?: boolean }\nexport type DefaultQuestion = Pick<ModelQuestion, 'id' | 'options' | 'multi_select'>\n\nconst RECOMMENDED_SUFFIX = /\\s*(?:\\((?:recommended|推荐)\\)|((?:recommended|推荐)))\\s*$/i\n\n/** Whether one option label carries the conventional recommendation suffix. */\nexport function isRecommended(label: unknown) {\n return typeof label === 'string' && RECOMMENDED_SUFFIX.test(label)\n}\n\n/**\n * Build the default answer for a question batch.\n *\n * Single-select always picks the first option. Multi-select picks every\n * recommended option; when none is recommended it picks the first option.\n * A question with no options is skipped with an empty selected list. The\n * returned object is marked autoSelected so the model can tell it apart from\n * a human answer.\n * @param questions - model-facing question items (raw args shape).\n * @returns an answer batch with autoSelected true.\n */\nexport function buildDefaultAnswer(questions: readonly DefaultQuestion[]): AskUserQuestionAnswer & { autoSelected: true } {\n const answers: AskUserQuestionAnswer['answers'] = []\n for (const question of questions) {\n const options = Array.isArray(question.options) ? question.options : []\n if (options.length === 0) {\n answers.push({ id: question.id, selected: [] })\n continue\n }\n let selected\n if (question.multi_select === true) {\n selected = options.filter(option => isRecommended(option.label)).map(option => option.label)\n if (selected.length === 0) selected = [options[0].label]\n } else {\n selected = [options[0].label]\n }\n answers.push({ id: question.id, selected: [...new Set(selected)] })\n }\n return { answers, autoSelected: true }\n}\n"]}
package/lib/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** dsh-better-ask-user host row: ask_user_question shadow, settings, PTC exemption. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import { Config } from './config.js';
4
+ export { Config };
5
+ export declare const name = "dsh-better-ask-user";
6
+ export declare const inject: string[];
7
+ export declare function apply(ctx: Context, config?: unknown): void;
package/lib/index.js ADDED
@@ -0,0 +1,48 @@
1
+ import { Config, readConfig as snapshotConfig } from './config.js';
2
+ import { createBetterAskTool } from './ask-tool.js';
3
+ import { mountPtcExemption } from './ptc.js';
4
+ import { mountLegacyMigration, mountSettings } from './settings.js';
5
+ export { Config };
6
+ export const name = 'dsh-better-ask-user';
7
+ export const inject = ['agents', 'tools', 'userQuestions'];
8
+ export function apply(ctx, config = {}) {
9
+ const readConfig = () => snapshotConfig(config);
10
+ mountSettings(ctx);
11
+ mountLegacyMigration(ctx);
12
+ mountPtcExemption(ctx);
13
+ const states = new Map();
14
+ function register(state) {
15
+ const tools = state.actor.get('tools');
16
+ const base = tools.get('ask_user_question', state.agent);
17
+ if (base === undefined)
18
+ return;
19
+ state.askDispose = tools.register(createBetterAskTool(ctx, base, readConfig));
20
+ }
21
+ function setup(agent) {
22
+ if (states.has(agent))
23
+ return states.get(agent);
24
+ const state = { agent, actor: agent.ctx, askDispose: undefined };
25
+ states.set(agent, state);
26
+ register(state);
27
+ return state;
28
+ }
29
+ function cleanup(state) {
30
+ state.askDispose?.();
31
+ state.askDispose = undefined;
32
+ }
33
+ ctx.on('agent/created', ({ agent }) => { setup(agent); });
34
+ ctx.on('agent/disposed', ({ agent }) => {
35
+ const state = states.get(agent);
36
+ if (state !== undefined)
37
+ cleanup(state);
38
+ states.delete(agent);
39
+ });
40
+ for (const agent of ctx.agents.list())
41
+ setup(agent);
42
+ ctx.effect(() => () => {
43
+ for (const state of states.values())
44
+ cleanup(state);
45
+ states.clear();
46
+ }, 'better-ask-user: per-agent controls');
47
+ }
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,UAAU,IAAI,cAAc,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAC5C,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAEnE,OAAO,EAAE,MAAM,EAAE,CAAA;AACjB,MAAM,CAAC,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AAA;QACpB,KAAK,CAAC,UAAU,GAAG,SAAS,CAAA;IAC9B,CAAC;IAED,GAAG,CAAC,EAAE,CAAC,eAAe,EAAE,CAAC,EAAE,KAAK,EAAE,EAAa,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,CAAA,CAAC,CAAC,CAAC,CAAA;IACnE,GAAG,CAAC,EAAE,CAAC,gBAAgB,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,CAAC,KAAK,CAAC,CAAA;QACvC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IACtB,CAAC,CAAC,CAAA;IACF,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE;QAAE,KAAK,CAAC,KAAK,CAAC,CAAA;IACnD,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE;QACpB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE;YAAE,OAAO,CAAC,KAAK,CAAC,CAAA;QACnD,MAAM,CAAC,KAAK,EAAE,CAAA;IAChB,CAAC,EAAE,qCAAqC,CAAC,CAAA;AAC3C,CAAC","sourcesContent":["/** dsh-better-ask-user host row: ask_user_question shadow, settings, PTC exemption. */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { Config, readConfig as snapshotConfig } from './config.js'\nimport { createBetterAskTool } from './ask-tool.js'\nimport { mountPtcExemption } from './ptc.js'\nimport { mountLegacyMigration, mountSettings } from './settings.js'\n\nexport { Config }\nexport const name = 'dsh-better-ask-user'\nexport const inject = ['agents', 'tools', 'userQuestions']\n\ninterface AgentState {\n agent: Agent\n actor: Context\n askDispose: (() => void) | undefined\n}\n\nexport function apply(ctx: Context, config: unknown = {}) {\n const readConfig = () => snapshotConfig(config)\n mountSettings(ctx)\n mountLegacyMigration(ctx)\n mountPtcExemption(ctx)\n\n const states = new Map<Agent, AgentState>()\n\n function register(state: AgentState) {\n const tools = state.actor.get('tools')!\n const base = tools.get('ask_user_question', state.agent)\n if (base === undefined) return\n state.askDispose = tools.register(createBetterAskTool(ctx, base, readConfig))\n }\n\n function setup(agent: Agent) {\n if (states.has(agent)) return states.get(agent)\n const state: AgentState = { agent, actor: agent.ctx, askDispose: undefined }\n states.set(agent, state)\n register(state)\n return state\n }\n\n function cleanup(state: AgentState) {\n state.askDispose?.()\n state.askDispose = undefined\n }\n\n ctx.on('agent/created', ({ agent }): undefined => { setup(agent) })\n ctx.on('agent/disposed', ({ agent }) => {\n const state = states.get(agent)\n if (state !== undefined) cleanup(state)\n states.delete(agent)\n })\n for (const agent of ctx.agents.list()) setup(agent)\n ctx.effect(() => () => {\n for (const state of states.values()) cleanup(state)\n states.clear()\n }, 'better-ask-user: per-agent controls')\n}\n"]}
package/lib/ptc.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Register ask_user_question with the shared PTC deadline exemption service. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ export declare function mountPtcExemption(ctx: Context): void;
package/lib/ptc.js ADDED
@@ -0,0 +1,13 @@
1
+ export function mountPtcExemption(ctx) {
2
+ if (typeof ctx.inject !== 'function')
3
+ return;
4
+ ctx.inject(['betterPtc'], (runtime) => {
5
+ if (runtime?.betterPtc === undefined)
6
+ return;
7
+ const dispose = runtime.betterPtc.register('ask_user_question');
8
+ if (typeof runtime.effect === 'function') {
9
+ runtime.effect(() => dispose, 'better-ask-user: PTC deadline exemption');
10
+ }
11
+ });
12
+ }
13
+ //# sourceMappingURL=ptc.js.map
package/lib/ptc.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ptc.js","sourceRoot":"","sources":["../src/ptc.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,iBAAiB,CAAC,GAAY;IAC5C,IAAI,OAAO,GAAG,CAAC,MAAM,KAAK,UAAU;QAAE,OAAM;IAC5C,GAAG,CAAC,MAAM,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE;QACpC,IAAI,OAAO,EAAE,SAAS,KAAK,SAAS;YAAE,OAAM;QAC5C,MAAM,OAAO,GAAG,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAA;QAC/D,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;YACzC,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,yCAAyC,CAAC,CAAA;QAC1E,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["/** Register ask_user_question with the shared PTC deadline exemption service. */\nimport type { Context } from '@deepseek-ai/cordis'\n\nexport function mountPtcExemption(ctx: Context) {\n if (typeof ctx.inject !== 'function') return\n ctx.inject(['betterPtc'], (runtime) => {\n if (runtime?.betterPtc === undefined) return\n const dispose = runtime.betterPtc.register('ask_user_question')\n if (typeof runtime.effect === 'function') {\n runtime.effect(() => dispose, 'better-ask-user: PTC deadline exemption')\n }\n })\n}\n"]}
@@ -0,0 +1,36 @@
1
+ /** Use the custom browser settings page and migrate the legacy goal wait. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ export interface SettingsService {
4
+ writable?: boolean;
5
+ describe(): unknown | Promise<unknown>;
6
+ update(ns: string, patch: {
7
+ questionTimeoutSeconds: number;
8
+ }, revision: unknown): unknown | Promise<unknown>;
9
+ }
10
+ export declare const LEGACY_GOAL_NS = "dsh-better-goal";
11
+ export declare const ASK_NS = "dsh-better-ask-user";
12
+ export declare const MAX_QUESTION_TIMEOUT_SECONDS = 2147483;
13
+ /**
14
+ * Copy an explicit legacy dsh-better-goal questionTimeoutSeconds into this
15
+ * row's questionTimeoutSeconds. The target's explicit value always wins; the
16
+ * source's default 120 is not treated as a custom value. Safe to repeat.
17
+ * @param service - settings service with describe / update.
18
+ * @returns a status report.
19
+ */
20
+ export declare function migrateLegacyQuestionTimeout(service: Partial<SettingsService> | null | undefined): Promise<{
21
+ status: string;
22
+ error?: undefined;
23
+ value?: undefined;
24
+ } | {
25
+ status: string;
26
+ error: string;
27
+ value?: undefined;
28
+ } | {
29
+ status: string;
30
+ value: number;
31
+ error?: undefined;
32
+ }>;
33
+ /** Use the custom browser settings page instead of a generated form. */
34
+ export declare function mountSettings(ctx: Context): void;
35
+ /** Run the legacy goal-wait migration once the settings service is available. */
36
+ export declare function mountLegacyMigration(ctx: Context): void;
@@ -0,0 +1,81 @@
1
+ export const LEGACY_GOAL_NS = 'dsh-better-goal';
2
+ export const ASK_NS = 'dsh-better-ask-user';
3
+ export const MAX_QUESTION_TIMEOUT_SECONDS = 2147483;
4
+ const WAIT_MS = 3000;
5
+ const WAIT_INTERVAL_MS = 50;
6
+ const sleep = (ms) => new Promise(resolve => { setTimeout(resolve, ms); });
7
+ function hasOwn(value, key) {
8
+ return value !== null && typeof value === 'object' && Object.hasOwn(value, key);
9
+ }
10
+ async function descriptor(service, ns) {
11
+ try {
12
+ const rows = await service.describe();
13
+ if (!Array.isArray(rows))
14
+ return undefined;
15
+ return rows.find((row) => row?.ns === ns);
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ function validSeconds(value) {
22
+ return value === -1 || (typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_QUESTION_TIMEOUT_SECONDS);
23
+ }
24
+ /**
25
+ * Copy an explicit legacy dsh-better-goal questionTimeoutSeconds into this
26
+ * row's questionTimeoutSeconds. The target's explicit value always wins; the
27
+ * source's default 120 is not treated as a custom value. Safe to repeat.
28
+ * @param service - settings service with describe / update.
29
+ * @returns a status report.
30
+ */
31
+ export async function migrateLegacyQuestionTimeout(service) {
32
+ if (typeof service?.describe !== 'function' || typeof service?.update !== 'function') {
33
+ return { status: 'unavailable' };
34
+ }
35
+ const deadline = Date.now() + WAIT_MS;
36
+ let source = await descriptor(service, LEGACY_GOAL_NS);
37
+ let target = await descriptor(service, ASK_NS);
38
+ while ((source === undefined || target === undefined) && Date.now() < deadline) {
39
+ await sleep(WAIT_INTERVAL_MS);
40
+ source = await descriptor(service, LEGACY_GOAL_NS);
41
+ target = await descriptor(service, ASK_NS);
42
+ }
43
+ if (source === undefined || target === undefined)
44
+ return { status: 'pending' };
45
+ if (!hasOwn(source.user, 'questionTimeoutSeconds'))
46
+ return { status: 'no-change' };
47
+ if (hasOwn(target.user, 'questionTimeoutSeconds'))
48
+ return { status: 'no-change' };
49
+ const value = source.value?.questionTimeoutSeconds;
50
+ if (!validSeconds(value))
51
+ return { status: 'no-change' };
52
+ if (service.writable === false)
53
+ return { status: 'pending' };
54
+ try {
55
+ await service.update(ASK_NS, { questionTimeoutSeconds: value }, target.revision);
56
+ }
57
+ catch (error) {
58
+ return { status: 'error', error: error instanceof Error ? error.message : String(error) };
59
+ }
60
+ const after = await descriptor(service, ASK_NS);
61
+ return after?.user?.questionTimeoutSeconds === value
62
+ ? { status: 'complete', value }
63
+ : { status: 'pending', value };
64
+ }
65
+ /** Use the custom browser settings page instead of a generated form. */
66
+ export function mountSettings(ctx) {
67
+ ctx.inject(['settings'], (inner) => {
68
+ const dispose = inner.settings.configure({ auto: false }, ctx.fiber);
69
+ inner.effect(() => dispose, 'better-ask-user: settings page');
70
+ });
71
+ }
72
+ /** Run the legacy goal-wait migration once the settings service is available. */
73
+ export function mountLegacyMigration(ctx) {
74
+ ctx.inject(['settings'], (inner) => {
75
+ const service = inner.settings ?? inner;
76
+ void migrateLegacyQuestionTimeout(service).catch((error) => {
77
+ inner.logger?.warn?.('better-ask-user: legacy question wait migration failed: ' + String(error));
78
+ });
79
+ });
80
+ }
81
+ //# sourceMappingURL=settings.js.map