@thready-web/dsh-bot-plugin 0.1.0-beta.2 → 0.1.0-beta.4

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.
@@ -0,0 +1,173 @@
1
+ export function createLogSource(ctx) {
2
+ const source = {
3
+ async head(sessionId) {
4
+ const cut = await observe(ctx, sessionId);
5
+ return cut.throughSeq;
6
+ },
7
+ async read(sessionId, afterSeq, throughSeq) {
8
+ const cut = await observe(ctx, sessionId);
9
+ const end = throughSeq == null ? cut.throughSeq : Math.min(throughSeq, cut.throughSeq);
10
+ const events = cut.events.filter(event => event.seq > afterSeq && event.seq <= end);
11
+ return { events, throughSeq: end };
12
+ },
13
+ async *tail(sessionId, afterSeq, signal) {
14
+ yield* tailEvents(ctx, source, sessionId, afterSeq, signal);
15
+ },
16
+ };
17
+ return source;
18
+ }
19
+ async function observe(ctx, sessionId, signal) {
20
+ const query = sessionQueryOf(ctx);
21
+ let observation;
22
+ try {
23
+ observation = await query.observeSession(sessionId, {
24
+ projectionMode: 'none',
25
+ ...(signal ? { signal } : {}),
26
+ });
27
+ const events = Array.isArray(observation.events)
28
+ ? observation.events.map(asLogEvent).filter((event) => event != null)
29
+ : [];
30
+ events.sort((left, right) => left.seq - right.seq);
31
+ const throughSeq = typeof observation.cursor === 'number' ? observation.cursor : lastSeq(events);
32
+ return { events, throughSeq };
33
+ }
34
+ catch (error) {
35
+ if (isMissingSession(error))
36
+ return { events: [], throughSeq: -1 };
37
+ throw error;
38
+ }
39
+ finally {
40
+ release(observation);
41
+ }
42
+ }
43
+ function sessionQueryOf(ctx) {
44
+ const found = (ctx.sessionQuery ?? ctx.get?.('sessionQuery'));
45
+ if (found?.observeSession == null)
46
+ throw new Error('sessionQuery is not available');
47
+ return found;
48
+ }
49
+ function asLogEvent(value) {
50
+ if (!value || typeof value !== 'object')
51
+ return null;
52
+ const record = value;
53
+ if (typeof record.type !== 'string' || typeof record.seq !== 'number' || !Number.isFinite(record.seq))
54
+ return null;
55
+ const time = typeof record.time === 'number' && Number.isFinite(record.time) ? record.time : 0;
56
+ const event = {
57
+ type: record.type,
58
+ seq: record.seq,
59
+ time,
60
+ data: record.data,
61
+ };
62
+ return {
63
+ ...event,
64
+ ...(record.surfaceOp !== undefined ? { surfaceOp: record.surfaceOp } : {}),
65
+ ...(record.sourceEventSeqs !== undefined ? { sourceEventSeqs: record.sourceEventSeqs } : {}),
66
+ };
67
+ }
68
+ function lastSeq(events) {
69
+ return events.length === 0 ? -1 : events[events.length - 1].seq;
70
+ }
71
+ function isMissingSession(error) {
72
+ const name = error instanceof Error ? error.name : '';
73
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
74
+ return (name === 'SessionPersistenceNotFoundError' ||
75
+ name === 'SessionNotFoundError' ||
76
+ code.includes('NOT_FOUND') ||
77
+ code.includes('MISSING_SESSION'));
78
+ }
79
+ function release(observation) {
80
+ try {
81
+ observation?.[Symbol.dispose]?.();
82
+ }
83
+ catch {
84
+ /* already released */
85
+ }
86
+ }
87
+ function sessionIdOf(session) {
88
+ if (!session || typeof session !== 'object')
89
+ return '';
90
+ const record = session;
91
+ const id = record.id ?? record.sessionId ?? record.header?.id ?? record.header?.sessionId;
92
+ return typeof id === 'string' ? id : '';
93
+ }
94
+ async function* tailEvents(ctx, source, sessionId, afterSeq, signal) {
95
+ const pending = [];
96
+ let notify = null;
97
+ const onEvent = (session, event) => {
98
+ if (sessionIdOf(session) !== sessionId)
99
+ return;
100
+ const row = asLogEvent(event);
101
+ if (!row)
102
+ return;
103
+ pending.push(row);
104
+ notify?.();
105
+ };
106
+ const off = ctx.on?.('session/event', onEvent, { global: true });
107
+ const wait = () => new Promise(resolve => {
108
+ if (signal.aborted) {
109
+ resolve();
110
+ return;
111
+ }
112
+ notify = resolve;
113
+ const onAbort = () => {
114
+ signal.removeEventListener('abort', onAbort);
115
+ resolve();
116
+ };
117
+ signal.addEventListener('abort', onAbort, { once: true });
118
+ });
119
+ try {
120
+ const { events, throughSeq } = await source.read(sessionId, afterSeq);
121
+ let cursor = throughSeq;
122
+ for (const event of events) {
123
+ if (signal.aborted)
124
+ return;
125
+ yield event;
126
+ }
127
+ const replay = pending.filter(event => event.seq > cursor).sort((left, right) => left.seq - right.seq);
128
+ pending.length = 0;
129
+ pending.push(...replay);
130
+ while (!signal.aborted) {
131
+ const index = pending.findIndex(event => event.seq === cursor + 1);
132
+ if (index >= 0) {
133
+ const event = pending.splice(index, 1)[0];
134
+ if (!event)
135
+ continue;
136
+ cursor = event.seq;
137
+ yield event;
138
+ continue;
139
+ }
140
+ await wait();
141
+ }
142
+ }
143
+ finally {
144
+ if (typeof off === 'function')
145
+ off();
146
+ }
147
+ }
148
+ export function logHasMessage(events, messageId) {
149
+ return events.some(event => (event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId)) ||
150
+ (event.type === 'user/message' && messageIdOf(event) === messageId));
151
+ }
152
+ export function spliceSeq(events, messageId) {
153
+ for (let index = events.length - 1; index >= 0; index -= 1) {
154
+ const event = events[index];
155
+ if (event && event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId))
156
+ return event.seq;
157
+ }
158
+ return null;
159
+ }
160
+ function insertedIds(event) {
161
+ const inserted = event.data && typeof event.data === 'object'
162
+ ? event.data.inserted
163
+ : undefined;
164
+ if (!Array.isArray(inserted))
165
+ return [];
166
+ return inserted.map(message => message?.id).filter((id) => typeof id === 'string');
167
+ }
168
+ function messageIdOf(event) {
169
+ if (!event.data || typeof event.data !== 'object')
170
+ return '';
171
+ const data = event.data;
172
+ return data.id ?? data.message?.id ?? '';
173
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Official session permission-preset surface for the desk settings UI.
3
+ *
4
+ * The write path is `ctx.permissionPresets.set(session, name)`. Auto is
5
+ * offered only when the live catalog includes it (the experimental package
6
+ * has registered it). This is a settings concern, not a transcript card.
7
+ */
8
+ import { toolError } from "./errors.js";
9
+ function sessionOf(ctx, sessionId) {
10
+ const agent = ctx.agents?.get?.(sessionId);
11
+ if (agent?.session)
12
+ return agent.session;
13
+ const sessions = ctx.sessions ?? ctx.get?.('sessions');
14
+ return sessions?.get?.(sessionId);
15
+ }
16
+ function optionList(value) {
17
+ if (!Array.isArray(value))
18
+ return [];
19
+ return value.flatMap(item => {
20
+ if (!item || typeof item !== 'object')
21
+ return [];
22
+ const row = item;
23
+ if (typeof row.value !== 'string' || row.value === '')
24
+ return [];
25
+ const option = {
26
+ value: row.value,
27
+ name: typeof row.name === 'string' && row.name !== '' ? row.name : row.value,
28
+ };
29
+ if (typeof row.description === 'string' && row.description !== '')
30
+ option.description = row.description;
31
+ return [option];
32
+ });
33
+ }
34
+ export function permissionView(ctx, sessionId) {
35
+ const service = ctx.get?.('permissionPresets');
36
+ if (!service || typeof service.catalog !== 'function') {
37
+ return {
38
+ available: false,
39
+ currentValue: '',
40
+ options: [],
41
+ defaultOptions: [],
42
+ defaultPreset: '',
43
+ autoAvailable: false,
44
+ };
45
+ }
46
+ const catalog = service.catalog() ?? {};
47
+ const options = optionList(catalog.options);
48
+ const defaultOptions = optionList(catalog.defaultOptions);
49
+ const session = sessionId !== '' ? sessionOf(ctx, sessionId) : undefined;
50
+ const currentValue = session && typeof service.current === 'function'
51
+ ? String(service.current(session) ?? '')
52
+ : typeof catalog.defaultPreset === 'string'
53
+ ? catalog.defaultPreset
54
+ : '';
55
+ return {
56
+ available: true,
57
+ currentValue,
58
+ options,
59
+ defaultOptions,
60
+ defaultPreset: typeof catalog.defaultPreset === 'string' ? catalog.defaultPreset : '',
61
+ autoAvailable: options.some(option => option.value === 'auto'),
62
+ };
63
+ }
64
+ export function setPermission(ctx, sessionId, name) {
65
+ if (typeof sessionId !== 'string' || sessionId === '') {
66
+ return toolError('VALIDATION', 'sessionId is required.');
67
+ }
68
+ if (typeof name !== 'string' || name === '' || name === 'custom') {
69
+ return toolError('VALIDATION', 'A selectable preset name is required.');
70
+ }
71
+ const service = ctx.get?.('permissionPresets');
72
+ if (!service || typeof service.set !== 'function') {
73
+ return toolError('UNAVAILABLE', 'Official permission presets are not composed on this host.');
74
+ }
75
+ const session = sessionOf(ctx, sessionId);
76
+ if (!session)
77
+ return toolError('NOT_FOUND', 'No live session is available for this permission change.');
78
+ try {
79
+ service.set(session, name);
80
+ return { ok: true, ...permissionView(ctx, sessionId) };
81
+ }
82
+ catch (error) {
83
+ const message = error instanceof Error ? error.message : 'The permission preset could not be changed.';
84
+ return toolError('VALIDATION', message);
85
+ }
86
+ }
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Official ask_user_question answerer for the desk UI.
3
+ *
4
+ * Open calls can be completed only by returning from the
5
+ * `user-questions/request` waterfall. `userQuestions.answer` is only for
6
+ * continued (timed/pending) questions. This listener is prepended so the
7
+ * typpert `$events` remote answerer cannot intercept the request before the
8
+ * desk can submit it. The official blocking legacy tool does not set
9
+ * `wait.callId`; timed requests do.
10
+ */
11
+ import { toolError } from "./errors.js";
12
+ export function questionRejection(code, message) {
13
+ const error = new Error(message);
14
+ error.code = code;
15
+ error.name = 'UserQuestionError';
16
+ return error;
17
+ }
18
+ const answerers = new Map();
19
+ export function publishQuestionAnswerer(dataDir, answerer) {
20
+ if (answerer)
21
+ answerers.set(dataDir, answerer);
22
+ else
23
+ answerers.delete(dataDir);
24
+ }
25
+ export function questionAnswererFor(dataDir) {
26
+ return answerers.get(dataDir) ?? null;
27
+ }
28
+ export function abortedQuestion(cause) {
29
+ const error = new Error('ask_user_question was aborted before the user answered', cause === undefined ? undefined : { cause });
30
+ error.code = 'ASK_ABORTED';
31
+ return error;
32
+ }
33
+ export function sessionIdOf(agent) {
34
+ if (!agent || typeof agent !== 'object')
35
+ return '';
36
+ if (typeof agent.session === 'string' && agent.session !== '')
37
+ return agent.session;
38
+ if (typeof agent.id === 'string' && agent.id !== '')
39
+ return agent.id;
40
+ return '';
41
+ }
42
+ export function callIdOf(request) {
43
+ const callId = request.wait?.callId;
44
+ return typeof callId === 'string' && callId !== '' ? callId : undefined;
45
+ }
46
+ function sameIds(questions, answers) {
47
+ if (questions.length !== answers.length)
48
+ return false;
49
+ const ids = new Set(answers.map(item => item.id));
50
+ return ids.size === answers.length && questions.every(item => ids.has(item.id));
51
+ }
52
+ /**
53
+ * Build the official answer batch from a desk submission, preserving exact
54
+ * question ids and option labels. Does not invent answers.
55
+ */
56
+ export function officialAnswerFrom(questions, submitted) {
57
+ if (!Array.isArray(questions) || questions.length === 0) {
58
+ return { ok: false, code: 'VALIDATION', message: 'A question request is required.' };
59
+ }
60
+ if (!Array.isArray(submitted)) {
61
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
62
+ }
63
+ const answers = [];
64
+ const seen = new Set();
65
+ for (const item of submitted) {
66
+ if (!item || typeof item !== 'object') {
67
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
68
+ }
69
+ if (typeof item.id !== 'string' || item.id === '' || seen.has(item.id)) {
70
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
71
+ }
72
+ const question = questions.find(entry => entry.id === item.id);
73
+ if (!question) {
74
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
75
+ }
76
+ if (!Array.isArray(item.selected) || item.selected.some(value => typeof value !== 'string')) {
77
+ return { ok: false, code: 'BAD_ANSWER', message: 'Each answer must include a selected label array.' };
78
+ }
79
+ const options = question.options ?? [];
80
+ for (const label of item.selected) {
81
+ if (options.length === 0 || !options.some(option => option.label === label)) {
82
+ return { ok: false, code: 'BAD_ANSWER', message: 'A selected label is not one of the offered options.' };
83
+ }
84
+ }
85
+ if (question.multiSelect !== true && item.selected.length > 1) {
86
+ return { ok: false, code: 'BAD_ANSWER', message: 'This question does not allow more than one selected option.' };
87
+ }
88
+ if (item.custom !== undefined && typeof item.custom !== 'string') {
89
+ return { ok: false, code: 'BAD_ANSWER', message: 'A custom answer must be a string.' };
90
+ }
91
+ const custom = typeof item.custom === 'string' ? item.custom : undefined;
92
+ if (question.multiSelect !== true && custom !== undefined && custom !== '' && item.selected.length > 0) {
93
+ return {
94
+ ok: false,
95
+ code: 'BAD_ANSWER',
96
+ message: 'A single-select custom answer must leave selected empty.',
97
+ };
98
+ }
99
+ seen.add(item.id);
100
+ const entry = { id: item.id, selected: [...item.selected] };
101
+ if (custom !== undefined && custom !== '')
102
+ entry.custom = custom;
103
+ answers.push(entry);
104
+ }
105
+ if (!sameIds(questions, answers)) {
106
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
107
+ }
108
+ return { ok: true, answer: { answers } };
109
+ }
110
+ function matchPending(pending, sessionId, callId, questionIds) {
111
+ const sessionRows = [...pending].filter(entry => entry.sessionId === sessionId);
112
+ if (callId) {
113
+ const byCall = sessionRows.filter(entry => entry.callId === callId);
114
+ if (byCall.length === 1)
115
+ return { ok: true, entry: byCall[0] };
116
+ if (byCall.length > 1) {
117
+ return { ok: false, code: 'CONFLICT', message: 'Multiple open questions match this call.' };
118
+ }
119
+ }
120
+ const byQuestions = sessionRows.filter(entry => {
121
+ if (entry.callId && callId && entry.callId !== callId)
122
+ return false;
123
+ const ids = entry.request.questions.map(question => question.id);
124
+ return (ids.length === questionIds.length &&
125
+ ids.every((id, index) => id === questionIds[index] || questionIds.includes(id)) &&
126
+ questionIds.every(id => ids.includes(id)));
127
+ });
128
+ if (byQuestions.length === 1)
129
+ return { ok: true, entry: byQuestions[0] };
130
+ if (byQuestions.length > 1) {
131
+ return { ok: false, code: 'CONFLICT', message: 'Multiple open questions match this session.' };
132
+ }
133
+ if (questionIds.length === 0 && !callId && sessionRows.length === 1) {
134
+ return { ok: true, entry: sessionRows[0] };
135
+ }
136
+ if (questionIds.length === 0 && !callId && sessionRows.length > 1) {
137
+ return { ok: false, code: 'CONFLICT', message: 'Multiple open questions match this session.' };
138
+ }
139
+ return { ok: false, code: 'NOT_FOUND', message: 'No open user-questions request matches this session.' };
140
+ }
141
+ /** Structural official answer batch. Option membership is checked only against an open request. */
142
+ export function wellFormedAnswerBatch(submitted) {
143
+ if (!Array.isArray(submitted) || submitted.length === 0) {
144
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
145
+ }
146
+ const answers = [];
147
+ const seen = new Set();
148
+ for (const item of submitted) {
149
+ if (!item || typeof item !== 'object' || typeof item.id !== 'string' || item.id === '' || seen.has(item.id)) {
150
+ return { ok: false, code: 'BAD_ANSWER', message: 'The answer batch must name each question exactly once.' };
151
+ }
152
+ if (!Array.isArray(item.selected) || item.selected.some(value => typeof value !== 'string')) {
153
+ return { ok: false, code: 'BAD_ANSWER', message: 'Each answer must include a selected label array.' };
154
+ }
155
+ if (item.custom !== undefined && typeof item.custom !== 'string') {
156
+ return { ok: false, code: 'BAD_ANSWER', message: 'A custom answer must be a string.' };
157
+ }
158
+ seen.add(item.id);
159
+ const entry = { id: item.id, selected: [...item.selected] };
160
+ if (typeof item.custom === 'string' && item.custom !== '')
161
+ entry.custom = item.custom;
162
+ answers.push(entry);
163
+ }
164
+ return { ok: true, answer: { answers } };
165
+ }
166
+ export function createQuestionAnswerer() {
167
+ const pending = new Set();
168
+ let host = null;
169
+ function detach(entry) {
170
+ if (!pending.has(entry))
171
+ return false;
172
+ pending.delete(entry);
173
+ if (entry.onAbort && entry.request.signal) {
174
+ entry.request.signal.removeEventListener('abort', entry.onAbort);
175
+ }
176
+ entry.waitAbort?.abort();
177
+ return true;
178
+ }
179
+ function attachTimedWait(entry) {
180
+ const timed = entry.request.wait?.timed === true;
181
+ const callId = entry.callId;
182
+ const attachWait = host?.userQuestions?.attachWait;
183
+ const agent = host?.agents?.get?.(entry.sessionId);
184
+ if (!timed || !callId || !attachWait || !agent)
185
+ return;
186
+ const waitAbort = new AbortController();
187
+ entry.waitAbort = waitAbort;
188
+ void (async () => {
189
+ try {
190
+ for await (const frame of attachWait(agent, callId, waitAbort.signal)) {
191
+ if (!pending.has(entry) || entry.takeTime)
192
+ return;
193
+ if (typeof frame?.remainingMs === 'number' && Number.isFinite(frame.remainingMs)) {
194
+ entry.remainingMs = Math.max(0, frame.remainingMs);
195
+ entry.deadline = Date.now() + entry.remainingMs;
196
+ }
197
+ }
198
+ }
199
+ catch {
200
+ /* claim ended with the wait */
201
+ }
202
+ })();
203
+ }
204
+ function delegate(entry) {
205
+ if (!detach(entry))
206
+ return;
207
+ Promise.resolve().then(entry.next).then(entry.resolve, entry.reject);
208
+ }
209
+ function waitForAnswer(request, next) {
210
+ const sessionId = sessionIdOf(request.agent);
211
+ if (sessionId === '')
212
+ return next();
213
+ return new Promise((resolve, reject) => {
214
+ const entry = {
215
+ request,
216
+ sessionId,
217
+ callId: callIdOf(request),
218
+ next,
219
+ resolve,
220
+ reject,
221
+ };
222
+ const onAbort = () => {
223
+ if (!detach(entry))
224
+ return;
225
+ reject(abortedQuestion());
226
+ };
227
+ entry.onAbort = onAbort;
228
+ pending.add(entry);
229
+ if (request.signal?.aborted) {
230
+ onAbort();
231
+ return;
232
+ }
233
+ request.signal?.addEventListener('abort', onAbort, { once: true });
234
+ attachTimedWait(entry);
235
+ });
236
+ }
237
+ async function handle(request, next) {
238
+ return waitForAnswer(request, next);
239
+ }
240
+ function submitOpen(input) {
241
+ const questionIds = input.answers.map(item => item.id);
242
+ const matched = matchPending(pending, input.sessionId, input.callId, questionIds);
243
+ if (!matched.ok) {
244
+ if (matched.code === 'CONFLICT')
245
+ return toolError(matched.code, matched.message);
246
+ return null;
247
+ }
248
+ const built = officialAnswerFrom(matched.entry.request.questions, input.answers);
249
+ if (!built.ok)
250
+ return toolError(built.code, built.message);
251
+ if (!detach(matched.entry))
252
+ return toolError('CONFLICT', 'This question was already answered.');
253
+ matched.entry.resolve(built.answer);
254
+ return { ok: true, path: 'open', answer: built.answer };
255
+ }
256
+ function submitContinued(input) {
257
+ const userQuestions = host?.userQuestions;
258
+ const agents = host?.agents;
259
+ if (!userQuestions || !agents) {
260
+ return toolError('NOT_FOUND', 'No open user-questions request matches this session.');
261
+ }
262
+ const callId = input.callId;
263
+ if (typeof callId !== 'string' || callId === '') {
264
+ return toolError('VALIDATION', 'callId is required to answer a continued question.');
265
+ }
266
+ const shaped = wellFormedAnswerBatch(input.answers);
267
+ if (!shaped.ok)
268
+ return toolError(shaped.code, shaped.message);
269
+ const agent = agents.get(input.sessionId);
270
+ if (!agent)
271
+ return toolError('NOT_FOUND', 'No live agent is available for this session.');
272
+ const agentSession = sessionIdOf(agent);
273
+ if (agentSession !== '' && agentSession !== input.sessionId) {
274
+ return toolError('FORBIDDEN', 'The answer does not belong to this session.');
275
+ }
276
+ try {
277
+ const accepted = userQuestions.answer(agent, callId, shaped.answer);
278
+ if (!accepted)
279
+ return toolError('NOT_FOUND', 'This question is not a continued user-questions call.');
280
+ return { ok: true, path: 'continued', answer: shaped.answer };
281
+ }
282
+ catch (error) {
283
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
284
+ ? error.code
285
+ : 'UNAVAILABLE';
286
+ const message = error instanceof Error ? error.message : 'The continued question could not be answered.';
287
+ if (code === 'BAD_ANSWER')
288
+ return toolError('BAD_ANSWER', message);
289
+ if (code === 'REPLY_QUEUED')
290
+ return toolError('CONFLICT', message);
291
+ if (code === 'CALLER_NOT_LIVE' || code === 'DELEGATED_CALLER')
292
+ return toolError('FORBIDDEN', message);
293
+ return toolError(code, message);
294
+ }
295
+ }
296
+ function submit(input) {
297
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
298
+ return toolError('VALIDATION', 'sessionId is required.');
299
+ }
300
+ const sessionId = input.sessionId;
301
+ const callId = typeof input.callId === 'string' && input.callId !== '' ? input.callId : undefined;
302
+ const answers = Array.isArray(input.answers) ? input.answers : null;
303
+ if (!answers)
304
+ return toolError('VALIDATION', 'answers is required.');
305
+ const open = submitOpen({ sessionId, callId, answers });
306
+ if (open)
307
+ return open;
308
+ return submitContinued({ sessionId, callId, answers });
309
+ }
310
+ function matchOpen(sessionId, callId, questionIds) {
311
+ return matchPending(pending, sessionId, callId, questionIds ?? []);
312
+ }
313
+ function cancel(input) {
314
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
315
+ return toolError('VALIDATION', 'sessionId is required.');
316
+ }
317
+ const questionIds = Array.isArray(input.answers) ? input.answers.map(item => item.id) : [];
318
+ const matched = matchOpen(input.sessionId, input.callId, questionIds);
319
+ if (!matched.ok)
320
+ return toolError(matched.code, matched.message);
321
+ if (!detach(matched.entry))
322
+ return toolError('CONFLICT', 'This question was already answered.');
323
+ matched.entry.reject(questionRejection('ASK_CANCELLED', 'The user requested changes or cancelled the question.'));
324
+ return { ok: true, path: 'cancelled' };
325
+ }
326
+ function timeout(input) {
327
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
328
+ return toolError('VALIDATION', 'sessionId is required.');
329
+ }
330
+ const matched = matchOpen(input.sessionId, input.callId);
331
+ if (!matched.ok)
332
+ return toolError(matched.code, matched.message);
333
+ if (matched.entry.request.wait?.timed !== true) {
334
+ return toolError('VALIDATION', 'Only a timed question can be settled as ASK_TIMED_OUT.');
335
+ }
336
+ if (!detach(matched.entry))
337
+ return toolError('CONFLICT', 'This question was already answered.');
338
+ matched.entry.reject(questionRejection('ASK_TIMED_OUT', 'The foreground answer window closed.'));
339
+ return { ok: true, path: 'timed-out' };
340
+ }
341
+ function takeTime(input) {
342
+ if (typeof input.sessionId !== 'string' || input.sessionId === '') {
343
+ return toolError('VALIDATION', 'sessionId is required.');
344
+ }
345
+ const matched = matchOpen(input.sessionId, input.callId);
346
+ if (!matched.ok)
347
+ return toolError(matched.code, matched.message);
348
+ matched.entry.takeTime = true;
349
+ matched.entry.remainingMs = undefined;
350
+ matched.entry.deadline = undefined;
351
+ return { ok: true, path: 'waiting' };
352
+ }
353
+ function remainingOf(entry) {
354
+ if (entry.takeTime)
355
+ return undefined;
356
+ if (typeof entry.deadline === 'number')
357
+ return Math.max(0, entry.deadline - Date.now());
358
+ return entry.remainingMs;
359
+ }
360
+ function snapshot(sessionId) {
361
+ return [...pending]
362
+ .filter(entry => !sessionId || entry.sessionId === sessionId)
363
+ .map(entry => {
364
+ const timed = entry.request.wait?.timed === true;
365
+ const remainingMs = remainingOf(entry);
366
+ const waitState = !timed
367
+ ? 'none'
368
+ : entry.takeTime
369
+ ? 'waiting'
370
+ : typeof remainingMs === 'number'
371
+ ? 'counting'
372
+ : 'waiting';
373
+ return {
374
+ sessionId: entry.sessionId,
375
+ callId: entry.callId,
376
+ timed,
377
+ waitState,
378
+ remainingMs,
379
+ questions: entry.request.questions,
380
+ };
381
+ });
382
+ }
383
+ function listen(ctx) {
384
+ host = ctx;
385
+ const dispose = ctx.on?.('user-questions/request', handle, true);
386
+ return () => {
387
+ if (typeof dispose === 'function')
388
+ dispose();
389
+ for (const entry of [...pending])
390
+ delegate(entry);
391
+ if (host === ctx)
392
+ host = null;
393
+ };
394
+ }
395
+ return {
396
+ listen,
397
+ handle,
398
+ submit,
399
+ cancel,
400
+ timeout,
401
+ takeTime,
402
+ snapshot,
403
+ pendingCount() {
404
+ return pending.size;
405
+ },
406
+ };
407
+ }