Repository navigation
Expand file tree
/
Copy pathtimed.ts
More file actions
212 lines (201 loc) · 9.23 KB
/
Copy pathtimed.ts
File metadata and controls
212 lines (201 loc) · 9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* Opt-in timed `ask_user_question` tool definition.
*/
import type { Context } from '@deepseek-ai/cordis'
import { defineTool, ToolArgsError, ToolContextUnavailableError, type ToolExecution } from '@deepseek-ai/dsh-tools'
import { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions'
import type {
AskUserQuestionAnswer, AskUserQuestionRequestEvent,
} from '@deepseek-ai/dsh-user-questions/types'
function validateTimeout(timeout: number): number {
if (timeout !== -1 && (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483)) {
throw new ToolArgsError(['timeout must be -1 or a positive integer up to 2147483 seconds'])
}
return timeout
}
function validateQuestionIds(questions: readonly { readonly id: string }[]): void {
const ids = new Set<string>()
for (const question of questions) {
if (ids.has(question.id)) throw new ToolArgsError([`question id ${JSON.stringify(question.id)} must be unique within this call`])
ids.add(question.id)
}
}
/** Model-facing meaning of a skipped answer item, shared by the blocking and timed descriptions. */
export const skippedAnswerGuidance = '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.'
const 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. ${skippedAnswerGuidance} `
+ 'A pending result instead means no answer batch arrived before the timeout and the user can still answer.'
/**
* Instruction the pending result carries in its `message` field. It is a field
* of the result value rather than prose beside it because the recorded result
* text is read back as one JSON object: the `userQuestions` projection decides
* from it that the call stays answerable, and the Client question row decides
* from it that the recorded result is the timeout, not an answer batch.
*/
const pendingNotice = '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.'
interface ToolQuestion {
readonly id: string
readonly question: string
readonly header?: string
readonly options?: { readonly label: string; readonly description?: string }[]
readonly multi_select?: boolean
}
interface ToolAnswerResult {
readonly answers: {
readonly id: string
readonly selected: string[]
readonly custom?: string
}[]
}
/**
* Translate the model schema into the service request without changing ownership.
* @param questions - Model-supplied questions in tool-schema form.
* @param exec - Execution context that owns the agent and cancellation signal.
* @returns The corresponding user-question service request.
*/
function questionRequest(
questions: readonly ToolQuestion[],
exec: Pick<ToolExecution, 'agent' | 'signal'>,
): AskUserQuestionRequestEvent {
return {
questions: questions.map(question => ({
id: question.id,
question: question.question,
...question.header !== undefined ? { header: question.header } : {},
...question.options !== undefined ? { options: question.options.map(option => ({ ...option })) } : {},
...question.multi_select !== undefined ? { multiSelect: question.multi_select } : {},
})),
...exec.agent !== undefined ? { agent: exec.agent } : {},
signal: exec.signal,
}
}
/**
* Copy service-owned answer arrays into the model-facing result.
* @param result - Answer returned by the user-question service.
* @returns A detached model-facing answer payload.
*/
function answerResult(result: AskUserQuestionAnswer): ToolAnswerResult {
return {
answers: result.answers.map(answer => ({
id: answer.id,
selected: [...answer.selected],
...answer.custom !== undefined ? { custom: answer.custom } : {},
})),
}
}
/**
* Register the opt-in timed tool definition.
* @param ctx - Agent-scoped context receiving the tool.
* @param timeout - Default foreground wait in seconds.
*/
export function registerTimedAskUser(ctx: Context, timeout = 120): void {
const defaultTimeout = validateTimeout(timeout)
/* jscpd:ignore-start -- The timed schema intentionally shares question fields with the legacy tool. */
ctx.tools.register(defineTool({
name: 'ask_user_question',
description,
parameters: {
questions: {
type: 'array',
required: true,
description: 'Questions to ask the user.',
items: {
type: 'object',
additionalProperties: true,
properties: {
id: { type: 'string', required: true, description: 'Stable id for this question; echoed in the answer.' },
question: { type: 'string', required: true, description: 'The specific question to ask the user.' },
header: {
type: 'string',
description: 'Optional short heading for the question, such as "Confirm" or "Choose Mode".',
},
options: {
type: 'array',
description: 'Optional choices to show the user. If you recommend one, put it first and append "(Recommended)" to that label.',
items: {
type: 'object',
additionalProperties: true,
properties: {
label: { type: 'string', required: true, description: 'Short user-facing option label.' },
description: { type: 'string', description: 'One sentence explaining the tradeoff or impact.' },
},
},
},
multi_select: {
type: 'boolean',
description: 'Whether the user may select more than one option. Defaults to false.',
},
},
},
},
// The `userQuestions` projection reads this parameter's presence out of
// the logged request header to tell a timed call from a legacy one.
[TIMED_WAIT_PARAMETER]: {
type: 'integer',
description: `Wait seconds for the entire batch (default ${defaultTimeout}); omit unless the user specifies a duration. Use -1 only when an answer is required before proceeding.`,
},
},
output: {
schema: {
oneOf: [
{
type: 'object', additionalProperties: false,
properties: {
pending: {
type: 'boolean', enum: [true], required: true,
description: 'True when the foreground wait expired before the user submitted an answer batch. The questions remain answerable; this is not a skipped answer.',
},
callId: { type: 'string', required: true, description: 'Tool call whose unanswered questions remain pending.' },
message: {
type: 'string', required: true,
description: 'How to continue while the questions stay answerable.',
},
},
},
{
type: 'object', additionalProperties: false,
properties: {
answers: {
type: 'array', required: true,
description: 'Submitted answer batch with one item per question. A skipped question has empty selected and no custom; unlike pending, the user has completed the batch.',
items: {
type: 'object', additionalProperties: false,
properties: {
id: { type: 'string', required: true, description: 'Stable question id echoed from the request.' },
selected: {
type: 'array', required: true, items: { type: 'string' },
description: 'Selected option labels. Empty with no custom means the user explicitly skipped this question.',
},
custom: { type: 'string', description: 'Optional free-form answer; omitted for a skipped question.' },
},
},
},
},
},
],
},
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
},
async execute(args, exec) {
const timeout = validateTimeout(args.timeout ?? defaultTimeout)
validateQuestionIds(args.questions)
const request = questionRequest(args.questions, exec)
if (timeout !== -1) {
if (exec.agent === undefined) throw new ToolContextUnavailableError('timed questions require a live agent')
const result = await ctx.userQuestions.askTimed({ ...request, agent: exec.agent }, exec.callId, timeout * 1000)
return 'pending' in result ? { ...result, message: pendingNotice } : answerResult(result)
}
// `wait` without `timed`: this tool's indefinite form still keys the
// Client card by call id, so the UI can reopen a closed panel from the
// tool call. The legacy tool keeps its unkeyed request.
const result = await ctx.userQuestions.ask({ ...request, wait: { callId: exec.callId } })
return answerResult(result)
},
}))
/* jscpd:ignore-end */
}