@deepseek-ai/dsh-user-questions 0.2.2-rc.1 → 0.2.2-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/lib/index.js +5 -6
- package/lib/typert.host.js +23 -7
- package/lib/typert.remote-client.d.ts.map +1 -0
- package/lib/types/index.d.ts +4 -5
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +5 -6
- package/lib/types/index.js.map +1 -0
- package/lib/types/projection.d.ts.map +1 -0
- package/lib/types/projection.js.map +1 -0
- package/lib/types/timed-wait.d.ts.map +1 -0
- package/lib/types/timed-wait.js.map +1 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js.map +1 -0
- package/package.json +21 -17
- package/src/index.ts +364 -0
- package/src/projection.ts +331 -0
- package/src/timed-wait.ts +83 -0
- package/src/types.ts +180 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Service Definition for the user-questions capability seam (`ctx.userQuestions`): a UI-backed service for
|
|
3
|
+
* pausing an agent tool call until the human answers a question. The model-
|
|
4
|
+
* facing tool lives in `@deepseek-ai/dsh-tool-ask-user`; UI packages compose
|
|
5
|
+
* answerers on the Agent-scoped Cordis waterfall.
|
|
6
|
+
*
|
|
7
|
+
* @module @deepseek-ai/dsh-user-questions
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { Context, Service } from '@deepseek-ai/cordis'
|
|
11
|
+
import type {} from '@deepseek-ai/dsh-agent'
|
|
12
|
+
import { createUserMessage, HarnessError, type MessageId, type ToolCallId, type UserMessage } from '@deepseek-ai/dsh-llm'
|
|
13
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
14
|
+
import { scopeTarget } from '@deepseek-ai/dsh-scope'
|
|
15
|
+
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
|
16
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
17
|
+
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
|
18
|
+
import z from '@deepseek-ai/schemastery'
|
|
19
|
+
import { userQuestionProjectionDefinition, type UserQuestionProjectionState } from './projection.ts'
|
|
20
|
+
import { TimedQuestionWait } from './timed-wait.ts'
|
|
21
|
+
|
|
22
|
+
declare module '@deepseek-ai/cordis' {
|
|
23
|
+
interface Context {
|
|
24
|
+
userQuestions: UserQuestionService
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
import type {
|
|
29
|
+
AskUserQuestionAnswer, AskUserQuestionRequestEvent, PendingUserQuestion,
|
|
30
|
+
} from './types.ts'
|
|
31
|
+
|
|
32
|
+
export type {
|
|
33
|
+
AskUserQuestionAnswer, AskUserQuestionAnswerItem, AskUserQuestionIntent, AskUserQuestionItem,
|
|
34
|
+
AskUserQuestionOption, PendingUserQuestion, SettledUserQuestion, UserQuestionProjectionView,
|
|
35
|
+
UserQuestionState,
|
|
36
|
+
} from './types.ts'
|
|
37
|
+
export { isTimedAskUserQuestionSchema, TIMED_WAIT_PARAMETER } from './projection.ts'
|
|
38
|
+
|
|
39
|
+
/** Request for a human answer. */
|
|
40
|
+
export interface AskUserQuestionRequest extends AskUserQuestionRequestEvent {}
|
|
41
|
+
|
|
42
|
+
/** Timed ask result returned when the foreground answer window closes. */
|
|
43
|
+
export type TimedUserQuestionResult = AskUserQuestionAnswer | { pending: true; callId: ToolCallId }
|
|
44
|
+
|
|
45
|
+
/** Stable error taxonomy for user-questions failures. */
|
|
46
|
+
export class UserQuestionError extends HarnessError {
|
|
47
|
+
constructor(message: string, code: string, options?: ErrorOptions) {
|
|
48
|
+
super(message, code, options)
|
|
49
|
+
this.name = 'UserQuestionError'
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function abortedQuestion(cause?: unknown): UserQuestionError {
|
|
54
|
+
return new UserQuestionError(
|
|
55
|
+
'ask_user_question was aborted before the user answered',
|
|
56
|
+
'ASK_ABORTED',
|
|
57
|
+
cause === undefined ? undefined : { cause },
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
62
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function restoreUserQuestionError(reason: unknown): unknown {
|
|
66
|
+
if (reason instanceof UserQuestionError) return reason
|
|
67
|
+
if (isRecord(reason)
|
|
68
|
+
&& reason.name === 'UserQuestionError'
|
|
69
|
+
&& typeof reason.message === 'string'
|
|
70
|
+
&& typeof reason.code === 'string') {
|
|
71
|
+
return new UserQuestionError(reason.message, reason.code, { cause: reason })
|
|
72
|
+
}
|
|
73
|
+
return reason
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type QueuedReply = { messageId: MessageId; claimedTurn?: number }
|
|
77
|
+
|
|
78
|
+
/** `ctx.userQuestions`: validation plus the scoped answerer waterfall. */
|
|
79
|
+
export class UserQuestionService extends TypertRemoteService {
|
|
80
|
+
static Config = z.object({})
|
|
81
|
+
private userQuestionProjectionHandle: ProjectionHandle<UserQuestionProjectionState> | undefined
|
|
82
|
+
private readonly waits = new Map<Agent, Map<ToolCallId, TimedQuestionWait>>()
|
|
83
|
+
private readonly queuedReplies = new WeakMap<Session, Map<ToolCallId, QueuedReply>>()
|
|
84
|
+
|
|
85
|
+
constructor(ctx: Context) {
|
|
86
|
+
super(ctx, 'userQuestions')
|
|
87
|
+
ctx.effect(() => () => {
|
|
88
|
+
for (const calls of this.waits.values()) {
|
|
89
|
+
for (const wait of calls.values()) wait.close(abortedQuestion())
|
|
90
|
+
}
|
|
91
|
+
this.waits.clear()
|
|
92
|
+
}, 'userQuestions: foreground waits')
|
|
93
|
+
ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
|
|
94
|
+
const source = message.source
|
|
95
|
+
if (source.kind !== 'user-question-reply') return
|
|
96
|
+
const calls = this.queuedReplies.get(agent.session) ?? new Map<ToolCallId, QueuedReply>()
|
|
97
|
+
const reply = calls.get(source.callId)
|
|
98
|
+
if (reply === undefined) {
|
|
99
|
+
calls.set(source.callId, { messageId: message.id, claimedTurn: turn })
|
|
100
|
+
this.queuedReplies.set(agent.session, calls)
|
|
101
|
+
} else if (reply.messageId === message.id) {
|
|
102
|
+
reply.claimedTurn = turn
|
|
103
|
+
}
|
|
104
|
+
}, { global: true })
|
|
105
|
+
ctx.on('agent/inbox/discarded', ({ agent, message }) => {
|
|
106
|
+
const source = message.source
|
|
107
|
+
if (source.kind === 'user-question-reply') this.releaseReply(agent.session, source.callId, message.id)
|
|
108
|
+
}, { global: true })
|
|
109
|
+
ctx.on('session/event', (session, event) => {
|
|
110
|
+
if (event.type === 'user/message') {
|
|
111
|
+
const source = event.data.source
|
|
112
|
+
if (source.kind === 'user-question-reply') this.releaseReply(session, source.callId, event.data.id)
|
|
113
|
+
} else if (event.type === 'turn/end') {
|
|
114
|
+
const calls = this.queuedReplies.get(session)
|
|
115
|
+
if (calls === undefined) return
|
|
116
|
+
for (const [callId, reply] of calls) {
|
|
117
|
+
if (reply.claimedTurn === event.data.turn) calls.delete(callId)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}, { global: true })
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private releaseReply(session: Session, callId: ToolCallId, messageId: MessageId): void {
|
|
124
|
+
const calls = this.queuedReplies.get(session)
|
|
125
|
+
if (calls?.get(callId)?.messageId !== messageId) return
|
|
126
|
+
calls.delete(callId)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
protected async [Service.init](): Promise<void> {
|
|
130
|
+
const binding = this.ctx.inject(['sessionProjections'], async (ctx) => {
|
|
131
|
+
this.userQuestionProjectionHandle = await ctx.sessionProjections.register(userQuestionProjectionDefinition)
|
|
132
|
+
return () => { this.userQuestionProjectionHandle = undefined }
|
|
133
|
+
})
|
|
134
|
+
if (this.ctx.get('sessionProjections') !== undefined) await binding
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private assertLiveRoot(agent: Agent): void {
|
|
138
|
+
const agents = this.ctx.get('agents')
|
|
139
|
+
if (agents === undefined || agents.get(agent.id) !== agent) {
|
|
140
|
+
throw new UserQuestionError(
|
|
141
|
+
'human interaction requires the exact live calling agent when an agent is supplied',
|
|
142
|
+
'CALLER_NOT_LIVE')
|
|
143
|
+
}
|
|
144
|
+
if (agent.session.header.origin === 'subagent') {
|
|
145
|
+
throw new UserQuestionError(
|
|
146
|
+
'human interaction is unavailable while the calling agent is owned by another live agent; '
|
|
147
|
+
+ "include the unresolved question or decision in the child agent's final result",
|
|
148
|
+
'DELEGATED_CALLER')
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private continued(agent: Agent): readonly PendingUserQuestion[] {
|
|
153
|
+
return this.userQuestionProjectionHandle?.stateOf(agent.session).questions.active.filter(question => question.state === 'continued') ?? []
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Answer a continued question. The reply is steered into the agent as a
|
|
158
|
+
* user message whose source names the call; that message is also the
|
|
159
|
+
* record that closes the question in the projection.
|
|
160
|
+
* @param agent - Live root agent for the owning Session.
|
|
161
|
+
* @param callId - Continued question identity.
|
|
162
|
+
* @param answer - Complete structured answer batch, one item per question of the call.
|
|
163
|
+
* @returns Whether the question is still continued; an accepted reply stays
|
|
164
|
+
* queued until the agent admits its user message.
|
|
165
|
+
* @throws {UserQuestionError} `BAD_ANSWER` when the batch does not name each
|
|
166
|
+
* question of the call exactly once, or `REPLY_QUEUED` when a reply is
|
|
167
|
+
* already waiting for admission.
|
|
168
|
+
*/
|
|
169
|
+
@Remote
|
|
170
|
+
answer(agent: Agent, callId: ToolCallId, answer: AskUserQuestionAnswer): boolean {
|
|
171
|
+
this.assertLiveRoot(agent)
|
|
172
|
+
const question = this.continued(agent).find(item => item.callId === callId)
|
|
173
|
+
if (question === undefined) return false
|
|
174
|
+
const queued = this.queuedReplies.get(agent.session)
|
|
175
|
+
const matches = (message: UserMessage): boolean =>
|
|
176
|
+
message.source.kind === 'user-question-reply' && message.source.callId === callId
|
|
177
|
+
if (queued?.has(callId) || agent.inbox.nextTurn.some(matches) || agent.inbox.nextStep.some(matches)) {
|
|
178
|
+
throw new UserQuestionError('a reply is already queued for this question', 'REPLY_QUEUED')
|
|
179
|
+
}
|
|
180
|
+
// The gateway validated the batch's shape from the type; the model-facing
|
|
181
|
+
// contract also promises one item per question, which only this owner of
|
|
182
|
+
// the asked questions can check before the batch reaches the model.
|
|
183
|
+
const answered = new Set(answer.answers.map(item => item.id))
|
|
184
|
+
if (answered.size !== answer.answers.length
|
|
185
|
+
|| question.questions.length !== answer.answers.length
|
|
186
|
+
|| !question.questions.every(item => answered.has(item.id))) {
|
|
187
|
+
throw new UserQuestionError(
|
|
188
|
+
`the answer batch for ${callId} must name each of its ${String(question.questions.length)} questions exactly once`,
|
|
189
|
+
'BAD_ANSWER')
|
|
190
|
+
}
|
|
191
|
+
const message = createUserMessage({
|
|
192
|
+
source: { kind: 'user-question-reply', callId, outcome: 'answered' },
|
|
193
|
+
content: [{
|
|
194
|
+
type: 'text',
|
|
195
|
+
text: JSON.stringify({
|
|
196
|
+
kind: 'answer_to_pending_question', tool: 'ask_user_question', callId,
|
|
197
|
+
questions: question.questions, answers: answer.answers,
|
|
198
|
+
}),
|
|
199
|
+
}],
|
|
200
|
+
})
|
|
201
|
+
const calls = queued ?? new Map<ToolCallId, QueuedReply>()
|
|
202
|
+
calls.set(callId, { messageId: message.id })
|
|
203
|
+
this.queuedReplies.set(agent.session, calls)
|
|
204
|
+
try {
|
|
205
|
+
agent.steer(message)
|
|
206
|
+
} catch (error: unknown) {
|
|
207
|
+
this.releaseReply(agent.session, callId, message.id)
|
|
208
|
+
throw error
|
|
209
|
+
}
|
|
210
|
+
return true
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Let one answer UI hold a live timed wait. Closing the stream releases its claim.
|
|
215
|
+
* @param agent - Live root agent owning the question.
|
|
216
|
+
* @param callId - Foreground tool call to attach to.
|
|
217
|
+
* @param signal - Remote stream cancellation, including Client disconnect.
|
|
218
|
+
* @returns One Host-computed remaining duration, or no frames once the wait ended.
|
|
219
|
+
*/
|
|
220
|
+
@Remote({ mode: 'stream' })
|
|
221
|
+
async *attachWait(agent: Agent, callId: ToolCallId, signal: AbortSignal): AsyncIterable<{ remainingMs: number }> {
|
|
222
|
+
this.assertLiveRoot(agent)
|
|
223
|
+
const wait = this.waits.get(agent)?.get(callId)
|
|
224
|
+
if (wait !== undefined) yield* wait.attach(signal)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Foreground wait whose first settlement the Client decides: the Client
|
|
229
|
+
* rejects with `ASK_TIMED_OUT` when its countdown ends, and this method maps
|
|
230
|
+
* that code to the pending result.
|
|
231
|
+
* @param request - Questions, live owner agent, and abort signal.
|
|
232
|
+
* @param callId - Tool call identity the Client card is keyed by.
|
|
233
|
+
* @param timeoutMs - Positive foreground wait in milliseconds.
|
|
234
|
+
* @returns The answer when it arrives inside the window, otherwise a pending
|
|
235
|
+
* result, also when no connected Client claimed the request by the deadline.
|
|
236
|
+
* @throws {UserQuestionError} `BAD_TIMEOUT` for a non-integer, non-positive,
|
|
237
|
+
* or oversized wait.
|
|
238
|
+
*/
|
|
239
|
+
async askTimed(
|
|
240
|
+
request: AskUserQuestionRequest & { agent: Agent },
|
|
241
|
+
callId: ToolCallId,
|
|
242
|
+
timeoutMs: number,
|
|
243
|
+
): Promise<TimedUserQuestionResult> {
|
|
244
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {
|
|
245
|
+
throw new UserQuestionError('timeout must fit a positive platform timer', 'BAD_TIMEOUT')
|
|
246
|
+
}
|
|
247
|
+
this.assertLiveRoot(request.agent)
|
|
248
|
+
const calls = this.waits.get(request.agent) ?? new Map<ToolCallId, TimedQuestionWait>()
|
|
249
|
+
if (calls.has(callId)) throw new UserQuestionError('the question call already has a foreground wait', 'DUPLICATE_WAIT')
|
|
250
|
+
const wait = new TimedQuestionWait(Date.now() + timeoutMs, request.signal,
|
|
251
|
+
new UserQuestionError('ask_user_question timed out before the user answered', 'ASK_TIMED_OUT'))
|
|
252
|
+
calls.set(callId, wait)
|
|
253
|
+
this.waits.set(request.agent, calls)
|
|
254
|
+
try {
|
|
255
|
+
try {
|
|
256
|
+
return await this.ask({ ...request, signal: wait.signal, wait: { callId, timed: true } })
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (wait.signal.aborted) throw wait.signal.reason
|
|
259
|
+
if (error instanceof UserQuestionError && error.code === 'NO_PROVIDER') {
|
|
260
|
+
await wait.done
|
|
261
|
+
throw wait.signal.reason
|
|
262
|
+
}
|
|
263
|
+
throw error
|
|
264
|
+
}
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if (error instanceof UserQuestionError && error.code === 'ASK_TIMED_OUT') return { pending: true, callId }
|
|
267
|
+
if (wait.signal.aborted) throw abortedQuestion(error)
|
|
268
|
+
throw error
|
|
269
|
+
} finally {
|
|
270
|
+
wait.close(abortedQuestion())
|
|
271
|
+
calls.delete(callId)
|
|
272
|
+
if (calls.size === 0) this.waits.delete(request.agent)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Ask the scoped answerer waterfall and wait for the user's answer.
|
|
278
|
+
*
|
|
279
|
+
* When a caller supplies an agent, human interaction is valid only for the
|
|
280
|
+
* exact live instance of an ordinary Session. Explicit subagent origin
|
|
281
|
+
* rejects delegated callers; historical ordinary forks may retain parent
|
|
282
|
+
* metadata and still ask normally.
|
|
283
|
+
*
|
|
284
|
+
* @param request Questions, owner agent, and abort signal.
|
|
285
|
+
* @returns The answer chosen or typed by the human.
|
|
286
|
+
* @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal
|
|
287
|
+
* is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent
|
|
288
|
+
* is not the registry's exact live instance, or `DELEGATED_CALLER` when
|
|
289
|
+
* that live agent has subagent origin.
|
|
290
|
+
*/
|
|
291
|
+
async ask(request: AskUserQuestionRequest): Promise<AskUserQuestionAnswer> {
|
|
292
|
+
if (request.signal?.aborted) {
|
|
293
|
+
throw abortedQuestion()
|
|
294
|
+
}
|
|
295
|
+
if (request.questions.length === 0) {
|
|
296
|
+
throw new UserQuestionError('ask_user_question requires at least one question', 'EMPTY_QUESTIONS')
|
|
297
|
+
}
|
|
298
|
+
const agent = request.agent
|
|
299
|
+
if (agent !== undefined) this.assertLiveRoot(agent)
|
|
300
|
+
for (const question of request.questions) {
|
|
301
|
+
const intent = question.intent
|
|
302
|
+
if (intent === undefined) continue
|
|
303
|
+
const labels = intent.kind === 'approval'
|
|
304
|
+
? [intent.approve, intent.reject, ...intent.always === undefined ? [] : [intent.always]]
|
|
305
|
+
: [intent.approve]
|
|
306
|
+
const options = question.options ?? []
|
|
307
|
+
const unoffered = labels.find(label => !options.some(option => option.label === label))
|
|
308
|
+
if (unoffered !== undefined) {
|
|
309
|
+
if (intent.kind === 'plan-review') {
|
|
310
|
+
throw new UserQuestionError(
|
|
311
|
+
`question ${question.id} declares intent ${intent.kind} whose approve label `
|
|
312
|
+
+ `${JSON.stringify(intent.approve)} names none of its options`,
|
|
313
|
+
'BAD_INTENT')
|
|
314
|
+
}
|
|
315
|
+
throw new UserQuestionError(`question ${question.id} declares intent ${intent.kind} whose action label `
|
|
316
|
+
+ `${JSON.stringify(unoffered)} names none of its options`, 'BAD_INTENT')
|
|
317
|
+
}
|
|
318
|
+
if (question.detail === undefined) {
|
|
319
|
+
const detail = intent.kind === 'approval' ? 'scope detail it requires' : 'detail it reviews'
|
|
320
|
+
throw new UserQuestionError(`question ${question.id} declares intent ${intent.kind} without the ${detail}`, 'BAD_INTENT')
|
|
321
|
+
}
|
|
322
|
+
if (intent.kind === 'approval') {
|
|
323
|
+
if (request.questions.length !== 1) {
|
|
324
|
+
throw new UserQuestionError(`approval presentation requires one question; received ${request.questions.length}`, 'BAD_INTENT')
|
|
325
|
+
}
|
|
326
|
+
if (question.multiSelect === true) {
|
|
327
|
+
throw new UserQuestionError(`approval question ${question.id} does not support multiSelect`, 'BAD_INTENT')
|
|
328
|
+
}
|
|
329
|
+
if (request.wait !== undefined) {
|
|
330
|
+
throw new UserQuestionError(`approval question ${question.id} requires a blocking request without wait`, 'BAD_INTENT')
|
|
331
|
+
}
|
|
332
|
+
if (new Set(labels).size !== labels.length) {
|
|
333
|
+
throw new UserQuestionError(`approval question ${question.id} requires distinct action labels; received ${JSON.stringify(labels)}`, 'BAD_INTENT')
|
|
334
|
+
}
|
|
335
|
+
if (options.length !== labels.length) {
|
|
336
|
+
throw new UserQuestionError(`approval question ${question.id} requires ${labels.length} options matching its actions; received ${options.length}`, 'BAD_INTENT')
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const noAnswerer = () => Promise.reject(new UserQuestionError(
|
|
341
|
+
'no user-questions answerer accepted the request',
|
|
342
|
+
'NO_PROVIDER',
|
|
343
|
+
))
|
|
344
|
+
try {
|
|
345
|
+
return await (agent === undefined
|
|
346
|
+
? this.ctx.waterfall('user-questions/request', request, noAnswerer)
|
|
347
|
+
: this.ctx.waterfall(
|
|
348
|
+
scopeTarget(agent, agent),
|
|
349
|
+
'user-questions/request',
|
|
350
|
+
{ ...request, agent },
|
|
351
|
+
noAnswerer,
|
|
352
|
+
))
|
|
353
|
+
} catch (error) {
|
|
354
|
+
const restored = restoreUserQuestionError(error)
|
|
355
|
+
if (restored instanceof UserQuestionError) throw restored
|
|
356
|
+
if (request.signal?.aborted) {
|
|
357
|
+
throw abortedQuestion(error)
|
|
358
|
+
}
|
|
359
|
+
throw restored
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export default UserQuestionService
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/** Fold of `ask_user_question` tool events into the answerable question set, and its Session projection. */
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { SessionLogOffset, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session'
|
|
4
|
+
import type { SessionEvent, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session'
|
|
5
|
+
import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
|
|
6
|
+
import type {} from '@deepseek-ai/dsh-agent/types'
|
|
7
|
+
import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types'
|
|
8
|
+
import { ToolCallId } from '@deepseek-ai/dsh-llm'
|
|
9
|
+
import type { ContentBlock, ToolSchema } from '@deepseek-ai/dsh-llm'
|
|
10
|
+
import type { AskUserQuestionAnswerItem, AskUserQuestionItem, AskUserQuestionOption, PendingUserQuestion, SettledUserQuestion, UserQuestionProjectionView } from './types.ts'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The pure fold state: whether the request header in effect declares the
|
|
14
|
+
* timed `ask_user_question` schema, and the question view that schema's
|
|
15
|
+
* calls build. Calls made under the blocking legacy schema never enter it.
|
|
16
|
+
*/
|
|
17
|
+
export interface UserQuestionFold {
|
|
18
|
+
readonly timed: boolean
|
|
19
|
+
readonly questions: UserQuestionProjectionView
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Host projection state; `questions` is the wire value, reused whenever an event changes nothing. */
|
|
23
|
+
export interface UserQuestionProjectionState extends UserQuestionFold {
|
|
24
|
+
readonly inheritedEventCount: SessionLogOffsetType
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Tool whose calls this projection tracks. */
|
|
28
|
+
export const ASK_USER_QUESTION_TOOL = 'ask_user_question'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Model-facing parameter only the timed `ask_user_question` schema declares.
|
|
32
|
+
* Its presence in the logged request header is what tells the fold that the
|
|
33
|
+
* `ask_user_question` calls that follow can be continued past a timeout; the
|
|
34
|
+
* blocking legacy schema never declares it.
|
|
35
|
+
*/
|
|
36
|
+
export const TIMED_WAIT_PARAMETER = 'timeout'
|
|
37
|
+
|
|
38
|
+
const toolOptionSchema = z.object({
|
|
39
|
+
label: z.string(),
|
|
40
|
+
description: z.string().optional(),
|
|
41
|
+
}).loose()
|
|
42
|
+
|
|
43
|
+
const toolQuestionSchema = z.object({
|
|
44
|
+
id: z.string(),
|
|
45
|
+
question: z.string(),
|
|
46
|
+
header: z.string().optional(),
|
|
47
|
+
options: z.array(toolOptionSchema).optional(),
|
|
48
|
+
multi_select: z.boolean().optional(),
|
|
49
|
+
}).loose()
|
|
50
|
+
|
|
51
|
+
const toolArgumentsSchema = z.object({
|
|
52
|
+
questions: z.array(toolQuestionSchema).min(1),
|
|
53
|
+
}).loose()
|
|
54
|
+
|
|
55
|
+
const optionSchema = z.object({
|
|
56
|
+
label: z.string(),
|
|
57
|
+
description: z.string().optional(),
|
|
58
|
+
}).strict().transform((option): AskUserQuestionOption => ({
|
|
59
|
+
label: option.label,
|
|
60
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
61
|
+
}))
|
|
62
|
+
|
|
63
|
+
const questionSchema = z.object({
|
|
64
|
+
id: z.string(),
|
|
65
|
+
question: z.string(),
|
|
66
|
+
detail: z.string().optional(),
|
|
67
|
+
header: z.string().optional(),
|
|
68
|
+
options: z.array(optionSchema).optional(),
|
|
69
|
+
multiSelect: z.boolean().optional(),
|
|
70
|
+
}).strict().transform((question): AskUserQuestionItem => ({
|
|
71
|
+
id: question.id,
|
|
72
|
+
question: question.question,
|
|
73
|
+
...(question.detail === undefined ? {} : { detail: question.detail }),
|
|
74
|
+
...(question.header === undefined ? {} : { header: question.header }),
|
|
75
|
+
...(question.options === undefined ? {} : { options: question.options }),
|
|
76
|
+
...(question.multiSelect === undefined ? {} : { multiSelect: question.multiSelect }),
|
|
77
|
+
}))
|
|
78
|
+
|
|
79
|
+
const pendingQuestionsSchema: z.ZodType<readonly PendingUserQuestion[]> = z.array(z.object({
|
|
80
|
+
callId: z.string().min(1).transform(ToolCallId),
|
|
81
|
+
questions: z.array(questionSchema).min(1),
|
|
82
|
+
state: z.enum(['open', 'continued']),
|
|
83
|
+
}).strict()).superRefine((active, context) => {
|
|
84
|
+
if (new Set(active.map(question => question.callId)).size !== active.length) {
|
|
85
|
+
context.addIssue({ code: 'custom', message: 'callIds must be unique' })
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
const answerSchema = z.object({
|
|
90
|
+
id: z.string(),
|
|
91
|
+
selected: z.array(z.string()),
|
|
92
|
+
custom: z.string().optional(),
|
|
93
|
+
}).strict().transform((answer): AskUserQuestionAnswerItem => ({
|
|
94
|
+
id: answer.id,
|
|
95
|
+
selected: answer.selected,
|
|
96
|
+
...(answer.custom === undefined ? {} : { custom: answer.custom }),
|
|
97
|
+
}))
|
|
98
|
+
|
|
99
|
+
const settledQuestionsSchema: z.ZodType<readonly SettledUserQuestion[]> = z.array(z.object({
|
|
100
|
+
callId: z.string().min(1).transform(ToolCallId),
|
|
101
|
+
answers: z.array(answerSchema),
|
|
102
|
+
}).strict())
|
|
103
|
+
|
|
104
|
+
const projectionViewSchema: z.ZodType<UserQuestionProjectionView> = z.object({
|
|
105
|
+
active: pendingQuestionsSchema,
|
|
106
|
+
settled: settledQuestionsSchema,
|
|
107
|
+
}).strict()
|
|
108
|
+
|
|
109
|
+
/** The `answers` batch as both the in-time tool result and the steered late reply spell it. */
|
|
110
|
+
const answerBatchSchema = z.object({ answers: z.array(answerSchema) }).loose()
|
|
111
|
+
|
|
112
|
+
/** A Session with no timed `ask_user_question` call yet, shared so the wire value stays referentially stable. */
|
|
113
|
+
const emptyView: UserQuestionProjectionView = { active: [], settled: [] }
|
|
114
|
+
|
|
115
|
+
const initialFold: UserQuestionFold = { timed: false, questions: emptyView }
|
|
116
|
+
|
|
117
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
118
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Whether one logged tool schema is the timed `ask_user_question` tool's.
|
|
123
|
+
* @param tool - One entry of a request header's assembled tool schemas.
|
|
124
|
+
* @returns True only for an `ask_user_question` schema whose parameters declare {@link TIMED_WAIT_PARAMETER}.
|
|
125
|
+
*/
|
|
126
|
+
export function isTimedAskUserQuestionSchema(tool: Pick<ToolSchema, 'name' | 'parameters'>): boolean {
|
|
127
|
+
if (tool.name !== ASK_USER_QUESTION_TOOL) return false
|
|
128
|
+
const properties: unknown = tool.parameters['properties']
|
|
129
|
+
return isRecord(properties) && TIMED_WAIT_PARAMETER in properties
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Read the question batch out of logged `ask_user_question` arguments.
|
|
134
|
+
* @param argumentsText - Raw JSON arguments recorded on the `tool/call` event.
|
|
135
|
+
* @returns The questions in service vocabulary, or null when the arguments are unreadable.
|
|
136
|
+
*/
|
|
137
|
+
export function questionsOf(argumentsText: string): readonly AskUserQuestionItem[] | null {
|
|
138
|
+
let parsed: unknown
|
|
139
|
+
try {
|
|
140
|
+
parsed = JSON.parse(argumentsText)
|
|
141
|
+
} catch (error) {
|
|
142
|
+
// Malformed model arguments never reached the tool; there is no card to show.
|
|
143
|
+
void error
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
const result = toolArgumentsSchema.safeParse(parsed)
|
|
147
|
+
if (!result.success) return null
|
|
148
|
+
return result.data.questions.map(question => ({
|
|
149
|
+
id: question.id,
|
|
150
|
+
question: question.question,
|
|
151
|
+
...(question.header === undefined ? {} : { header: question.header }),
|
|
152
|
+
...(question.options === undefined
|
|
153
|
+
? {}
|
|
154
|
+
: {
|
|
155
|
+
options: question.options.map(option => ({
|
|
156
|
+
label: option.label,
|
|
157
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
158
|
+
})),
|
|
159
|
+
}),
|
|
160
|
+
...(question.multi_select === undefined ? {} : { multiSelect: question.multi_select }),
|
|
161
|
+
}))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function isPendingResult(content: readonly ContentBlock[]): boolean {
|
|
165
|
+
const text = content.find(block => block.type === 'text')
|
|
166
|
+
if (text === undefined) return false
|
|
167
|
+
try {
|
|
168
|
+
const parsed: unknown = JSON.parse(text.text)
|
|
169
|
+
return typeof parsed === 'object' && parsed !== null && (parsed as { pending?: unknown }).pending === true
|
|
170
|
+
} catch (error) {
|
|
171
|
+
// A non-JSON result text is a failure message, never the pending payload.
|
|
172
|
+
void error
|
|
173
|
+
return false
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Read the answer batch out of one recorded text: a tool result or a late reply.
|
|
179
|
+
* @param content - Content blocks of the recorded message.
|
|
180
|
+
* @returns The batch, or null when the text carries none this reader can use.
|
|
181
|
+
*/
|
|
182
|
+
function answerBatchOf(content: readonly ContentBlock[]): readonly AskUserQuestionAnswerItem[] | null {
|
|
183
|
+
const text = content.find(block => block.type === 'text')
|
|
184
|
+
if (text === undefined) return null
|
|
185
|
+
let parsed: unknown
|
|
186
|
+
try {
|
|
187
|
+
parsed = JSON.parse(text.text)
|
|
188
|
+
} catch (error) {
|
|
189
|
+
// A failure result, a dismissal, and any other text that is not an answer JSON carries no batch.
|
|
190
|
+
void error
|
|
191
|
+
return null
|
|
192
|
+
}
|
|
193
|
+
const result = answerBatchSchema.safeParse(parsed)
|
|
194
|
+
return result.success ? result.data.answers : null
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Close one answerable question and keep the answers it settled with.
|
|
199
|
+
* A reply whose call is no longer answerable changes nothing.
|
|
200
|
+
* @param view - Current question state.
|
|
201
|
+
* @param callId - Call the result or reply named.
|
|
202
|
+
* @param answers - The batch it carried; empty when a late reply carried none.
|
|
203
|
+
* @returns The same view when that call was not answerable, otherwise the updated one.
|
|
204
|
+
*/
|
|
205
|
+
function settleQuestion(
|
|
206
|
+
view: UserQuestionProjectionView,
|
|
207
|
+
callId: string,
|
|
208
|
+
answers: readonly AskUserQuestionAnswerItem[],
|
|
209
|
+
): UserQuestionProjectionView {
|
|
210
|
+
const question = view.active.find(item => item.callId === callId)
|
|
211
|
+
if (question === undefined) return view
|
|
212
|
+
return {
|
|
213
|
+
active: view.active.filter(item => item.callId !== callId),
|
|
214
|
+
settled: [...view.settled, { callId: question.callId, answers }],
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Apply one Session event to this Session's question fold.
|
|
220
|
+
* A `request/header` decides, from the assembled tool schemas it records,
|
|
221
|
+
* whether the `ask_user_question` calls that follow are timed; a call made
|
|
222
|
+
* under the blocking legacy schema is never tracked, so a Session that only
|
|
223
|
+
* ever used that tool folds to the empty view. A tracked question stays
|
|
224
|
+
* answerable as `continued` in exactly two cases: the tool returned the
|
|
225
|
+
* pending payload, or Session resume repair appended the synthetic
|
|
226
|
+
* `TOOL_OUTCOME_UNKNOWN` result for a call the process never finished. An
|
|
227
|
+
* answer batch settles it with that batch; any failure drops it. A PTC
|
|
228
|
+
* sub-call enters the fold when its recorded result is pending. A late reply
|
|
229
|
+
* settles only when the agent admits its user message; queued inbox messages
|
|
230
|
+
* can still be discarded before that point.
|
|
231
|
+
* @param fold - Current fold state.
|
|
232
|
+
* @param event - Next Session event in append order.
|
|
233
|
+
* @returns The same fold when the event is unrelated, otherwise the updated one.
|
|
234
|
+
*/
|
|
235
|
+
export function applyUserQuestionEvent(fold: UserQuestionFold, event: SessionEvent): UserQuestionFold {
|
|
236
|
+
const view = fold.questions
|
|
237
|
+
switch (event.type) {
|
|
238
|
+
case 'request/header': {
|
|
239
|
+
// The log records the exact schema list the model saw; a seeded or
|
|
240
|
+
// tool-less header carries none, which reads as the legacy tool.
|
|
241
|
+
const tools: unknown = event.data.header.tools
|
|
242
|
+
const timed = Array.isArray(tools) && tools.some((tool: unknown) =>
|
|
243
|
+
isRecord(tool) && typeof tool.name === 'string' && isRecord(tool.parameters)
|
|
244
|
+
&& isTimedAskUserQuestionSchema({ name: tool.name, parameters: tool.parameters }))
|
|
245
|
+
return timed === fold.timed ? fold : { ...fold, timed }
|
|
246
|
+
}
|
|
247
|
+
case 'tool/call': {
|
|
248
|
+
if (!fold.timed || event.data.name !== ASK_USER_QUESTION_TOOL) return fold
|
|
249
|
+
const questions = questionsOf(event.data.arguments)
|
|
250
|
+
if (questions === null) return fold
|
|
251
|
+
const callId = event.data.callId
|
|
252
|
+
return {
|
|
253
|
+
...fold,
|
|
254
|
+
questions: {
|
|
255
|
+
...view,
|
|
256
|
+
active: [...view.active.filter(question => question.callId !== callId), { callId, questions, state: 'open' }],
|
|
257
|
+
},
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
case 'tool/result': {
|
|
261
|
+
const callId = event.data.message.toolCallId
|
|
262
|
+
if (!view.active.some(question => question.callId === callId)) return fold
|
|
263
|
+
if (isPendingResult(event.data.message.content) || event.data.error?.code === TOOL_OUTCOME_UNKNOWN) {
|
|
264
|
+
return {
|
|
265
|
+
...fold,
|
|
266
|
+
questions: {
|
|
267
|
+
...view,
|
|
268
|
+
active: view.active.map(question => question.callId === callId ? { ...question, state: 'continued' } : question),
|
|
269
|
+
},
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const answers = event.data.error === undefined && event.data.message.isError !== true
|
|
273
|
+
? answerBatchOf(event.data.message.content)
|
|
274
|
+
: null
|
|
275
|
+
return {
|
|
276
|
+
...fold,
|
|
277
|
+
questions: answers === null
|
|
278
|
+
? { ...view, active: view.active.filter(question => question.callId !== callId) }
|
|
279
|
+
: settleQuestion(view, callId, answers),
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
case 'tool/ptc-dispatch': {
|
|
283
|
+
if (event.data.name !== ASK_USER_QUESTION_TOOL || event.data.isError || !isPendingResult(event.data.content)) return fold
|
|
284
|
+
const questions = questionsOf(JSON.stringify(event.data.arguments))
|
|
285
|
+
if (questions === null) return fold
|
|
286
|
+
const callId = event.data.subCallId
|
|
287
|
+
return {
|
|
288
|
+
...fold,
|
|
289
|
+
questions: {
|
|
290
|
+
...view,
|
|
291
|
+
active: [...view.active.filter(question => question.callId !== callId), { callId, questions, state: 'continued' }],
|
|
292
|
+
},
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
case 'user/message': {
|
|
296
|
+
const source = event.data.source
|
|
297
|
+
if (source.kind !== 'user-question-reply') return fold
|
|
298
|
+
const questions = settleQuestion(view, source.callId, answerBatchOf(event.data.content) ?? [])
|
|
299
|
+
return questions === view ? fold : { ...fold, questions }
|
|
300
|
+
}
|
|
301
|
+
default:
|
|
302
|
+
return fold
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Fold a whole Session log into its question state.
|
|
308
|
+
* @param events - Session events in append order.
|
|
309
|
+
* @returns Open and continued timed calls in ask order, and settled ones in settlement order.
|
|
310
|
+
*/
|
|
311
|
+
export function foldUserQuestions(events: readonly SessionEvent[]): UserQuestionProjectionView {
|
|
312
|
+
return events.reduce(applyUserQuestionEvent, initialFold).questions
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Session projection exposing open, continued, and settled timed questions to every Client. */
|
|
316
|
+
export const userQuestionProjectionDefinition = {
|
|
317
|
+
key: 'userQuestions',
|
|
318
|
+
stateSchema: z.object({
|
|
319
|
+
inheritedEventCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).transform(SessionLogOffset),
|
|
320
|
+
timed: z.boolean(),
|
|
321
|
+
questions: projectionViewSchema,
|
|
322
|
+
}).strict(),
|
|
323
|
+
init: (_header, inheritedEventCount) => ({ inheritedEventCount, ...initialFold }),
|
|
324
|
+
apply: (state, event) => {
|
|
325
|
+
if (event.seq < state.inheritedEventCount) return state
|
|
326
|
+
const fold = applyUserQuestionEvent(state, event)
|
|
327
|
+
return fold === state ? state : { ...state, ...fold }
|
|
328
|
+
},
|
|
329
|
+
wire: { viewSchema: projectionViewSchema, view: state => state.questions },
|
|
330
|
+
stateVersion: 2,
|
|
331
|
+
} satisfies ProjectionDefinition<'userQuestions', UserQuestionProjectionState>
|