dsh-taskbridge 1.7.1 → 1.8.0

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 (75) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +21 -21
  3. package/README.md +149 -290
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +31 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +170 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +119 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/plugin-market.md +30 -30
  17. package/docs/redaction-contract.md +170 -170
  18. package/docs/releases/1.7.0.zh.md +11 -11
  19. package/docs/releases/1.8.0.zh.md +16 -0
  20. package/docs/runtime-compatibility.md +1 -1
  21. package/docs/taskbridge-upgrade.md +28 -28
  22. package/docs/taskdispatch-upgrade.md +25 -25
  23. package/docs/workspace-contract.md +538 -538
  24. package/docs/workspace-grouping.md +126 -126
  25. package/icon.svg +1 -1
  26. package/lib/client.d.ts +733 -699
  27. package/lib/client.js +7 -7
  28. package/locale/en.json +1 -1
  29. package/locale/zh.json +1 -1
  30. package/package.json +149 -144
  31. package/src/antigravity/installer.js +1046 -0
  32. package/src/antigravity/seam.js +142 -0
  33. package/src/auth/fence.js +361 -361
  34. package/src/auth/grants.js +789 -789
  35. package/src/client/api.js +143 -0
  36. package/src/client/index.jsx +113 -3
  37. package/src/client/sidebar.jsx +862 -862
  38. package/src/client/styles.js +624 -624
  39. package/src/client/task-cleanup.js +304 -304
  40. package/src/client/task-records-table.jsx +217 -217
  41. package/src/client/task-view.js +307 -307
  42. package/src/client/workspace-groups.js +482 -482
  43. package/src/client/workspaces-browser.jsx +770 -770
  44. package/src/codex/agent-ownership.js +270 -270
  45. package/src/codex/installer.js +3 -0
  46. package/src/codex/toml.js +784 -784
  47. package/src/config/redact.js +245 -245
  48. package/src/config/store.js +186 -186
  49. package/src/credentials/seam.js +202 -202
  50. package/src/http/respond.js +6 -5
  51. package/src/http/user-plane.js +72 -0
  52. package/src/index.js +25 -0
  53. package/src/jobs/diagnostics.js +15 -15
  54. package/src/jobs/plan-store.js +1020 -1020
  55. package/src/jobs/review-note.js +63 -63
  56. package/src/jobs/task-descriptions.js +82 -82
  57. package/src/jobs/task-display.js +73 -73
  58. package/src/jobs/task-tree.js +786 -786
  59. package/src/jobs/title.js +134 -134
  60. package/src/mcp/continuation.js +317 -317
  61. package/src/mcp/server.js +4 -1
  62. package/src/model/connectivity.js +371 -371
  63. package/src/model/discovery.js +582 -582
  64. package/src/model/native-catalog.js +68 -68
  65. package/src/model/openai-adapter.js +671 -671
  66. package/src/model/probe.js +264 -264
  67. package/src/model/providers.js +756 -756
  68. package/src/model/routing.js +321 -321
  69. package/src/runtime/permissions.js +1619 -1619
  70. package/src/runtime/question-call.js +162 -162
  71. package/src/runtime/questions.js +909 -909
  72. package/src/runtime/worker-prompt.js +60 -55
  73. package/src/workspace/audit.js +775 -775
  74. package/src/workspace/preflight.js +424 -424
  75. package/src/workspace/worktrees.js +679 -679
@@ -1,909 +1,909 @@
1
- // The per-run QUESTION bridge: ordinary `ask_user_question` calls from a delegated
2
- // worker, surfaced to the commander as a decision it can actually answer.
3
- //
4
- // The native seam is the Agent-scoped Cordis waterfall `'user-questions/request'`
5
- // (`@deepseek-ai/dsh-user-questions`):
6
- //
7
- // request = { questions: [{ id, question, header?, detail?, options?, multiSelect?,
8
- // intent? }], agent?, signal?, wait?: { callId, timed? } }
9
- // → { answers: [{ id, selected: string[], custom?: string }] }
10
- //
11
- // A question is NOT an approval: an `approval` intent is refused here so the permission
12
- // bridge stays the only channel that can grant anything.
13
- //
14
- // Two properties carry most of the design:
15
- //
16
- // * **The question is published WHOLE or refused.** A question set is only accepted if
17
- // its exact serialised form fits {@link QUESTION_BOUNDS.wireChars}, so no later layer
18
- // can shorten a question the commander is told it may answer. A set that cannot be
19
- // published intact is refused at once, with a code the worker can act on.
20
- // * **An answer is bound to a REAL native tool call.** The call id comes from the
21
- // request, is verified against the Session log, and is re-checked before the answer is
22
- // applied, so an answer can never be delivered to an expired or replaced call.
23
-
24
- import { QUESTION_CALL_BINDING } from './question-call.js';
25
- import { redactDeep } from '../config/redact.js';
26
-
27
- /** What one question answerer may do, as a closed vocabulary. */
28
- export const QUESTION_CODES = Object.freeze({
29
- unbound: 'QUESTION_UNBOUND',
30
- busy: 'QUESTION_BUSY',
31
- approvalIntent: 'QUESTION_APPROVAL_INTENT',
32
- answerInvalid: 'QUESTION_ANSWER_INVALID',
33
- questionNotFound: 'QUESTION_QUESTION_NOT_FOUND',
34
- questionSettled: 'QUESTION_QUESTION_SETTLED',
35
- notPending: 'QUESTION_NOT_PENDING',
36
- alreadyAnswered: 'QUESTION_ALREADY_ANSWERED',
37
- expired: 'QUESTION_EXPIRED',
38
- // The question set cannot be published whole, so it is refused instead of being shown
39
- // shortened. `QUESTION_PAYLOAD_TOO_LARGE` names the size bound explicitly.
40
- payloadTooLarge: 'QUESTION_PAYLOAD_TOO_LARGE',
41
- redacted: 'QUESTION_PAYLOAD_REDACTED',
42
- // The question's own identity (id) is missing, too long or duplicated.
43
- badIdentity: 'QUESTION_IDENTITY_INVALID',
44
- // No trustworthy native tool call could be bound to this question.
45
- noCall: 'QUESTION_CALL_UNVERIFIED',
46
- // The bound call is no longer live, so an answer must not be replayed onto it.
47
- callGone: 'QUESTION_CALL_GONE',
48
- });
49
-
50
- /** Where a pending question set puts the task. */
51
- export const QUESTION_PHASE = Object.freeze({
52
- pending: 'awaiting-question',
53
- });
54
-
55
- /** Fixed refusal reasons, stable machine strings the commander sees verbatim. */
56
- export const QUESTION_REASONS = Object.freeze({
57
- notArmed: 'the question bridge is not armed for this run',
58
- disposed: 'the question bridge was disposed, so no answer can be applied',
59
- foreignAgent: 'the question belongs to a different agent',
60
- busy: 'another question set is already pending for this run',
61
- approvalIntent: 'a question that presents an approval cannot be answered through the question channel',
62
- badBatch: 'the answer batch must name each asked question exactly once',
63
- unknownQuestion: 'the answer names a question that was not asked',
64
- unknownOption: 'the answer selects an option the question did not offer',
65
- tooManySelected: 'a single-select question takes exactly one option',
66
- noSelection: 'an answer must select an option or carry custom text',
67
- emptyCustom: 'custom text must be a non-empty string',
68
- longCustom: 'custom text exceeds the bound',
69
- expired: 'the question reached its deadline without an answer',
70
- cancelled: 'the asking tool withdrew the question',
71
- stop: 'the run stopped while the question was pending',
72
- dispose: 'the plugin was disposed while the question was pending',
73
- settled: 'the question set already settled',
74
- alreadyAnswered: 'this question set was already answered; an answer applies once',
75
- noQuestions: 'a question request carried no questions',
76
- tooManyQuestions: 'a question request carried more questions than this channel accepts',
77
- payloadTooLarge: 'the question set is too large to publish whole, so it cannot be answered here',
78
- badId: 'a question id is missing, empty, too long or duplicated',
79
- noCall: 'no native tool call could be bound to this question, so it cannot be answered here',
80
- callGone: 'the bound native tool call is no longer live',
81
- });
82
-
83
- /**
84
- * Default life of one pending question.
85
- *
86
- * Reusing the approval request's ten-minute default keeps ONE operator-facing number, and
87
- * it is finite on purpose: a question pauses the execution budget, so an unbounded wait
88
- * would let a run hang forever on a commander that never answers.
89
- */
90
- export const QUESTION_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
91
- /** Ceiling on a configured question life. */
92
- export const QUESTION_MAX_TIMEOUT_MS = 30 * 60 * 1000;
93
-
94
- /**
95
- * Bounds on one question set and one answer.
96
- *
97
- * `wireChars` is the important one: it is a budget on the EXACT JSON the commander will
98
- * be sent, escapes included. It is set well below the MCP tool-text bound (20 000) so the
99
- * question block, the receiving answer's other fields and a decision receipt can always
100
- * travel together. A set that does not fit is refused, never published shortened.
101
- */
102
- export const QUESTION_BOUNDS = Object.freeze({
103
- /** Maximum questions in one request. */
104
- questions: 24,
105
- /** Maximum options offered by one question. */
106
- options: 24,
107
- /** Maximum characters for a question's own text. */
108
- questionChars: 2_000,
109
- /** Maximum characters for a question's detail. */
110
- detailChars: 8_000,
111
- /** Maximum characters for a header. */
112
- headerChars: 200,
113
- /** Maximum characters for one option label. */
114
- optionLabelChars: 400,
115
- /** Maximum characters for one option description. */
116
- optionDescriptionChars: 1_000,
117
- /** Maximum characters accepted as a custom answer. */
118
- customChars: 4_000,
119
- /** Maximum characters for a question id. */
120
- idChars: 200,
121
- /**
122
- * Maximum characters of the exact serialised question block.
123
- *
124
- * Deliberately conservative: a wait answer also carries the task summary, routing and
125
- * metrics, and an answer receipt must fit beside a live question. 12 000 leaves that
126
- * room and is still far above any question a worker should ask.
127
- */
128
- wireChars: 12_000,
129
- });
130
-
131
- export const QUESTION_STATES = Object.freeze({
132
- pending: 'pending',
133
- answered: 'answered',
134
- expired: 'expired',
135
- cancelled: 'cancelled',
136
- refused: 'refused',
137
- });
138
-
139
- /** Raised for every refusal of the answer verb. `details` is bounded and secret-free. */
140
- export class QuestionError extends Error {
141
- /**
142
- * @param {string} code - stable machine code.
143
- * @param {string} message - operator-facing explanation.
144
- * @param {object} [details] - bounded, non-secret context.
145
- */
146
- constructor(code, message, details = {}) {
147
- super(message);
148
- this.name = 'QuestionError';
149
- this.code = code;
150
- this.details = details;
151
- }
152
- }
153
-
154
- /**
155
- * A copy of one question, exactly as the commander will be shown it.
156
- *
157
- * The id is used VERBATIM: it is the value the answer must quote and the value the native
158
- * answerer echoes, so trimming it or inventing one would break the binding. A question
159
- * with no usable id is refused by the caller.
160
- * @param {unknown} question - one native question item.
161
- * @returns {{ id: string, question: string, header: string | null, detail: string | null,
162
- * options: { label: string, description: string | null }[], multiSelect: boolean,
163
- * intent: string | null } | null} the projection, or null when unusable.
164
- */
165
- export function projectQuestion(question) {
166
- if (question === null || typeof question !== 'object' || Array.isArray(question)) return null;
167
- if (typeof question.id !== 'string' || question.id === '') return null;
168
- const text = typeof question.question === 'string' ? question.question : '';
169
- if (text.trim() === '') return null;
170
- const options = [];
171
- if (Array.isArray(question.options)) {
172
- for (const option of question.options) {
173
- if (option === null || typeof option !== 'object') return null;
174
- const label = typeof option.label === 'string' ? option.label : '';
175
- if (label === '') return null;
176
- options.push({
177
- label,
178
- description: typeof option.description === 'string' && option.description !== ''
179
- ? option.description
180
- : null,
181
- });
182
- }
183
- }
184
- const intent = question.intent !== null && typeof question.intent === 'object'
185
- && typeof question.intent.kind === 'string'
186
- ? question.intent.kind
187
- : null;
188
- return {
189
- id: question.id,
190
- question: text,
191
- header: typeof question.header === 'string' && question.header !== '' ? question.header : null,
192
- detail: typeof question.detail === 'string' && question.detail !== '' ? question.detail : null,
193
- options,
194
- multiSelect: question.multiSelect === true,
195
- intent,
196
- };
197
- }
198
-
199
- /**
200
- * The EXACT serialised form of a question set, as the commander receives it.
201
- *
202
- * Measured with `JSON.stringify`, so quotes, backslashes and other escapes count at their
203
- * real serialised width — a set whose text is 11 000 raw characters but 22 000 escaped
204
- * characters does NOT fit, and measuring `length` field by field would have missed it.
205
- * @param {object[]} questions - projected questions.
206
- * @returns {number} serialised length in UTF-16 units.
207
- */
208
- export function questionWireLength(questions) {
209
- return JSON.stringify(questions).length;
210
- }
211
-
212
- /**
213
- * Whether one projected question set fits every bound, measured on the real wire form.
214
- *
215
- * Returned as a fact rather than logged: a set that does not fit must be REFUSED, because
216
- * publishing it shortened would show the commander a question the worker never asked and
217
- * apply its answer to a call that expected something else.
218
- * @param {object[]} questions - projected questions.
219
- * @returns {{ ok: true } | { ok: false, code: string, reason: string, detail: string }} verdict.
220
- */
221
- export function questionsFit(questions) {
222
- if (!Array.isArray(questions) || questions.length === 0) {
223
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.noQuestions, detail: 'no questions were asked' };
224
- }
225
- if (questions.length > QUESTION_BOUNDS.questions) {
226
- return {
227
- ok: false,
228
- code: QUESTION_CODES.answerInvalid,
229
- reason: QUESTION_REASONS.tooManyQuestions,
230
- detail: `${questions.length} questions exceed the bound of ${QUESTION_BOUNDS.questions}`,
231
- };
232
- }
233
- const seen = new Set();
234
- for (const question of questions) {
235
- if (typeof question.id !== 'string' || question.id === '' || question.id.length > QUESTION_BOUNDS.idChars) {
236
- return { ok: false, code: QUESTION_CODES.badIdentity, reason: QUESTION_REASONS.badId, detail: 'a question id is missing or too long' };
237
- }
238
- if (seen.has(question.id)) {
239
- return { ok: false, code: QUESTION_CODES.badIdentity, reason: QUESTION_REASONS.badId, detail: `duplicate question id ${question.id}` };
240
- }
241
- seen.add(question.id);
242
- if (question.question.length > QUESTION_BOUNDS.questionChars) {
243
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `question ${question.id} is too long` };
244
- }
245
- if (question.detail !== null && question.detail.length > QUESTION_BOUNDS.detailChars) {
246
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `detail of ${question.id} is too long` };
247
- }
248
- if (question.header !== null && question.header.length > QUESTION_BOUNDS.headerChars) {
249
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `header of ${question.id} is too long` };
250
- }
251
- if (question.options.length > QUESTION_BOUNDS.options) {
252
- return {
253
- ok: false,
254
- code: QUESTION_CODES.answerInvalid,
255
- reason: QUESTION_REASONS.badBatch,
256
- detail: `${question.id} offers ${question.options.length} options, above the bound of ${QUESTION_BOUNDS.options}`,
257
- };
258
- }
259
- const labels = new Set();
260
- for (const option of question.options) {
261
- if (option.label.length > QUESTION_BOUNDS.optionLabelChars) {
262
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `an option label of ${question.id} is too long` };
263
- }
264
- if (option.description !== null && option.description.length > QUESTION_BOUNDS.optionDescriptionChars) {
265
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `an option description of ${question.id} is too long` };
266
- }
267
- // Two options with one label make an answer ambiguous: the worker could not tell
268
- // which one was chosen.
269
- if (labels.has(option.label)) {
270
- return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `${question.id} repeats the option label ${JSON.stringify(option.label)}` };
271
- }
272
- labels.add(option.label);
273
- }
274
- }
275
- const wire = questionWireLength(questions);
276
- if (wire > QUESTION_BOUNDS.wireChars) {
277
- return {
278
- ok: false,
279
- code: QUESTION_CODES.payloadTooLarge,
280
- reason: QUESTION_REASONS.payloadTooLarge,
281
- detail: `the question set serialises to ${wire} characters, above the publishable bound of ${QUESTION_BOUNDS.wireChars}`,
282
- wireChars: wire,
283
- limit: QUESTION_BOUNDS.wireChars,
284
- };
285
- }
286
- return { ok: true, wireChars: wire };
287
- }
288
-
289
- /**
290
- * Validate one answer batch against the questions that were ACTUALLY asked.
291
- *
292
- * A single-select question may carry BOTH a selection and custom text: the native tool
293
- * documents `selected` as allowed to accompany custom text, and the UI shows "Other"
294
- * beside the list. Only a multi-selection is refused there.
295
- * @param {object[]} asked - the projected questions of the live request.
296
- * @param {unknown} answers - the commander's proposed answers.
297
- * @returns {{ ok: true, answers: { id: string, selected: string[], custom?: string }[] }
298
- * | { ok: false, reason: string, detail: string }} verdict.
299
- */
300
- export function validateAnswers(asked, answers) {
301
- if (!Array.isArray(answers)) {
302
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: 'answers must be an array' };
303
- }
304
- const byId = new Map(asked.map((question) => [question.id, question]));
305
- // Membership and uniqueness across the WHOLE batch are checked FIRST, so a batch naming
306
- // a question nobody asked reports exactly that rather than whatever option it mentioned.
307
- const seenIds = new Set();
308
- for (const answer of answers) {
309
- if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
310
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: 'each answer must be an object' };
311
- }
312
- const id = typeof answer.id === 'string' ? answer.id : '';
313
- if (!byId.has(id)) {
314
- return { ok: false, reason: QUESTION_REASONS.unknownQuestion, detail: `no question with id ${JSON.stringify(id)} was asked` };
315
- }
316
- if (seenIds.has(id)) {
317
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `question ${id} is answered more than once` };
318
- }
319
- seenIds.add(id);
320
- }
321
- if (seenIds.size !== asked.length || !asked.every((question) => seenIds.has(question.id))) {
322
- return {
323
- ok: false,
324
- reason: QUESTION_REASONS.badBatch,
325
- detail: `the batch must name each of the ${asked.length} questions exactly once`,
326
- };
327
- }
328
- const normalized = [];
329
- for (const answer of answers) {
330
- const id = answer.id;
331
- const question = byId.get(id);
332
- const selected = answer.selected === undefined ? [] : answer.selected;
333
- if (!Array.isArray(selected) || selected.some((label) => typeof label !== 'string')) {
334
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `selected of ${id} must be an array of labels` };
335
- }
336
- const labels = question.options.map((option) => option.label);
337
- for (const label of selected) {
338
- if (!labels.includes(label)) {
339
- return { ok: false, reason: QUESTION_REASONS.unknownOption, detail: `${JSON.stringify(label)} is not an option of ${id}` };
340
- }
341
- }
342
- if (new Set(selected).size !== selected.length) {
343
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `selected of ${id} repeats a label` };
344
- }
345
- let custom;
346
- if (answer.custom !== undefined && answer.custom !== null) {
347
- if (typeof answer.custom !== 'string') {
348
- return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `custom of ${id} must be a string` };
349
- }
350
- if (answer.custom.length > QUESTION_BOUNDS.customChars) {
351
- return { ok: false, reason: QUESTION_REASONS.longCustom, detail: `custom of ${id} exceeds ${QUESTION_BOUNDS.customChars} characters` };
352
- }
353
- if (answer.custom.trim() === '') {
354
- return { ok: false, reason: QUESTION_REASONS.emptyCustom, detail: `custom of ${id} is empty` };
355
- }
356
- custom = answer.custom;
357
- }
358
- if (question.multiSelect !== true && selected.length > 1) {
359
- return { ok: false, reason: QUESTION_REASONS.tooManySelected, detail: `${id} is single-select and received ${selected.length} labels` };
360
- }
361
- if (selected.length === 0 && custom === undefined) {
362
- return {
363
- ok: false,
364
- reason: QUESTION_REASONS.noSelection,
365
- detail: question.options.length === 0
366
- ? `${id} offers no options, so it needs custom text`
367
- : `${id} carries neither a selection nor custom text`,
368
- };
369
- }
370
- normalized.push({ id, selected: [...selected], ...(custom === undefined ? {} : { custom }) });
371
- }
372
- return { ok: true, answers: normalized };
373
- }
374
-
375
- /**
376
- * One run's question bridge. Same shape as `PermissionBridge` on purpose: one Agent, one
377
- * outstanding request, a bounded evidence trail, a lifecycle that releases the waiter.
378
- */
379
- export class QuestionBridge {
380
- /**
381
- * @param {object} options - `taskId`, optional `connectionId`, `timeoutMs`, `now`,
382
- * `onPending`, `onSettled`, `logger`, `resolveCall` (the call-binding probe).
383
- */
384
- constructor(options) {
385
- if (typeof options?.taskId !== 'string' || options.taskId === '') {
386
- throw new TypeError('QuestionBridge needs the taskId it belongs to');
387
- }
388
- this.taskId = options.taskId;
389
- this.connectionId = typeof options.connectionId === 'string' ? options.connectionId : null;
390
- this.now = typeof options.now === 'function' ? options.now : () => Date.now();
391
- const configured = Number(options.timeoutMs);
392
- this.timeoutMs = Number.isFinite(configured) && configured > 0
393
- ? Math.min(Math.trunc(configured), QUESTION_MAX_TIMEOUT_MS)
394
- : QUESTION_DEFAULT_TIMEOUT_MS;
395
- this.onPending = typeof options.onPending === 'function' ? options.onPending : null;
396
- this.onSettled = typeof options.onSettled === 'function' ? options.onSettled : null;
397
- this.logger = options.logger ?? null;
398
- this.resolveCall = typeof options.resolveCall === 'function' ? options.resolveCall : null;
399
- this.armed = false;
400
- this.disposed = false;
401
- this.agent = null;
402
- this.session = null;
403
- this.boundSessionId = null;
404
- // The exact Agent/Session objects this bridge was armed with; a replaced object is a
405
- // different conversation even when its id was recycled.
406
- this.armAgent = null;
407
- this.armSession = null;
408
- this.pending = null;
409
- this.history = [];
410
- this.sequence = 0;
411
- }
412
-
413
- static get HISTORY_BOUND() {
414
- return 8;
415
- }
416
-
417
- /**
418
- * Bind the bridge to the Agent/Session it answers for.
419
- * @param {object} agent - the live native Agent the run will drive.
420
- * @returns {{ taskId: string, sessionId: string }} what was armed.
421
- * @throws {QuestionError} when the agent is unusable or is not the bound one.
422
- */
423
- arm(agent) {
424
- if (this.disposed) {
425
- throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.disposed);
426
- }
427
- const session = agent?.session ?? null;
428
- const sessionId = typeof session?.id === 'string' ? session.id : null;
429
- if (session === null || sessionId === null) {
430
- throw new QuestionError(QUESTION_CODES.unbound, 'the delegated agent exposes no session to bind questions to', {
431
- reason: 'no session',
432
- });
433
- }
434
- if (this.agent !== null && this.agent !== agent) {
435
- throw new QuestionError(QUESTION_CODES.unbound, 'the question bridge is already bound to another agent', {
436
- reason: 'agent mismatch',
437
- });
438
- }
439
- if (this.session !== null && this.session !== session) {
440
- throw new QuestionError(QUESTION_CODES.unbound, 'the question bridge is already bound to another session');
441
- }
442
- this.agent = agent;
443
- this.session = session;
444
- this.boundSessionId = sessionId;
445
- // The EXACT objects this bridge was armed with. `arm()` may be called again for the same
446
- // Agent (it is idempotent), but a replaced Agent or Session must be detectable, which is a
447
- // question of object identity rather than of ids.
448
- this.armAgent = agent;
449
- this.armSession = session;
450
- this.armed = true;
451
- return { taskId: this.taskId, sessionId };
452
- }
453
-
454
- /**
455
- * Whether this bridge answers one native question request: the EXACT live Agent object
456
- * and the same Session, because the seam passes the live Agent and object identity
457
- * cannot be forged from data.
458
- * @param {object} request - native question request.
459
- * @returns {boolean} true when this bridge owns the request.
460
- */
461
- owns(request) {
462
- if (this.armed !== true || this.disposed === true) return false;
463
- if (this.agent === null || this.session === null) return false;
464
- const agent = request?.agent;
465
- if (agent === null || agent === undefined || typeof agent !== 'object') return false;
466
- const session = agent.session;
467
- if (session === null || session === undefined || typeof session !== 'object') return false;
468
- if (agent !== this.agent) return false;
469
- if (session !== this.session) return false;
470
- if (this.boundSessionId !== null && typeof session.id === 'string' && session.id !== this.boundSessionId) return false;
471
- return true;
472
- }
473
-
474
- /** Whether any question of a set presents an approval decision. */
475
- static presentsApproval(questions) {
476
- return questions.some((question) => question.intent === 'approval');
477
- }
478
-
479
- /**
480
- * Answer one native question request.
481
- * @param {object} request - native question request.
482
- * @returns {Promise<{ answers: object[] }>} the commander's answer.
483
- * @throws {QuestionError} when this bridge cannot answer the request.
484
- */
485
- async answer(request) {
486
- if (this.armed !== true || this.disposed === true) {
487
- throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.notArmed);
488
- }
489
- if (!this.owns(request)) {
490
- throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.foreignAgent);
491
- }
492
- if (this.pending !== null) {
493
- throw new QuestionError(QUESTION_CODES.busy, QUESTION_REASONS.busy);
494
- }
495
- const raw = Array.isArray(request?.questions) ? request.questions : [];
496
- const questions = [];
497
- for (const item of raw) {
498
- const projected = projectQuestion(item);
499
- if (projected === null) {
500
- throw new QuestionError(QUESTION_CODES.badIdentity, 'a question could not be described', {
501
- reason: QUESTION_REASONS.badId,
502
- detail: 'a question needs a non-empty string id and a non-empty question',
503
- });
504
- }
505
- questions.push(projected);
506
- }
507
- const fit = questionsFit(questions);
508
- if (fit.ok !== true) {
509
- // Refused BEFORE anything is published: the commander is never offered a question
510
- // set this channel cannot carry whole, so it can never be answered from a
511
- // shortened copy.
512
- throw new QuestionError(fit.code, 'the question set cannot be published whole', fit);
513
- }
514
- if (JSON.stringify(redactDeep(questions)) !== JSON.stringify(questions)) {
515
- throw new QuestionError(QUESTION_CODES.redacted,
516
- 'the question contains private data that cannot be published intact; rephrase it without private values');
517
- }
518
- if (QuestionBridge.presentsApproval(questions)) {
519
- throw new QuestionError(QUESTION_CODES.approvalIntent, QUESTION_REASONS.approvalIntent, {
520
- reason: QUESTION_REASONS.approvalIntent,
521
- channel: 'permission',
522
- hint: 'request the exact tool call through the approval channel; a question cannot grant access',
523
- });
524
- }
525
- const bound = await this.bindCall(request);
526
- if (bound.ok !== true) {
527
- throw new QuestionError(bound.code, 'no live native tool call could be bound to this question', {
528
- reason: bound.reason,
529
- detail: bound.detail,
530
- });
531
- }
532
- if (!this.owns(request)) {
533
- throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.foreignAgent);
534
- }
535
- if (this.pending !== null) {
536
- throw new QuestionError(QUESTION_CODES.busy, QUESTION_REASONS.busy);
537
- }
538
- const signal = request?.signal ?? null;
539
- if (signal?.aborted === true) {
540
- throw new QuestionError(QUESTION_CODES.questionSettled, QUESTION_REASONS.cancelled);
541
- }
542
- const pending = this.createPending(questions, bound.call);
543
- return await this.waitForAnswer(pending, signal);
544
- }
545
-
546
- /**
547
- * Bind this question to the ONE native `ask_user_question` call that is executing it.
548
- *
549
- * The call id is taken from the request (`wait.callId`, which the native tool sets) and
550
- * then VERIFIED against the Session log by {@link QUESTION_CALL_BINDING}: exactly one
551
- * matching `tool/call` in the open turn, no recorded result for it, owned by this Agent.
552
- * A question that cannot be bound this way is refused rather than answered against a
553
- * guess — delivering an answer to the wrong call would resume an operation nobody asked
554
- * about.
555
- * @param {object} request - native question request.
556
- * @returns {Promise<{ ok: true, call: object } | { ok: false, code: string, reason: string, detail: string }>} binding.
557
- */
558
- async bindCall(request) {
559
- const declared = typeof request?.wait?.callId === 'string' ? request.wait.callId : '';
560
- const probe = typeof this.resolveCall === 'function' ? this.resolveCall : QUESTION_CALL_BINDING;
561
- let found;
562
- try {
563
- found = probe({
564
- session: this.session,
565
- agent: this.agent,
566
- declaredCallId: declared === '' ? null : declared,
567
- toolName: 'ask_user_question',
568
- });
569
- } catch (error) {
570
- return {
571
- ok: false,
572
- code: QUESTION_CODES.noCall,
573
- reason: QUESTION_REASONS.noCall,
574
- detail: `the call binding could not be read (${String(error?.code ?? 'error')})`,
575
- };
576
- }
577
- if (found === null || typeof found !== 'object' || found.ok !== true) {
578
- return {
579
- ok: false,
580
- code: QUESTION_CODES.noCall,
581
- reason: QUESTION_REASONS.noCall,
582
- detail: typeof found?.detail === 'string' ? found.detail : 'no unique open tool call matches this question',
583
- };
584
- }
585
- return {
586
- ok: true,
587
- call: { callId: found.callId, seq: found.seq, turn: found.turn ?? null },
588
- };
589
- }
590
-
591
- /**
592
- * Whether the bound call is still the live one this answer may resume.
593
- *
594
- * An id match alone is NOT enough, and the reproduction proved it: after
595
- * `turn/end, turn/start(turn2), tool/call c turn2` the same id `c` is a DIFFERENT call in a
596
- * different turn, so an answer bound to the first one would be delivered to an operation
597
- * that never asked. Nor is it enough that the bridge still holds *a* session: a replaced
598
- * Session object is a different conversation even when its id was recycled.
599
- *
600
- * So four facts must ALL still hold: the same Agent object, the same Session object, the
601
- * same Session id, and the same call at the same log offset in the same turn.
602
- * @param {object} pending - pending record.
603
- * @returns {boolean} true when the call is still live and still the same call.
604
- */
605
- callStillLive(pending) {
606
- if (pending?.call === null || pending?.call === undefined) return false;
607
- if (!this.owns({ agent: this.agent })) return false;
608
- // The Agent and the Session must still be the objects this bridge was armed with.
609
- if (this.armAgent === null || this.agent !== this.armAgent) return false;
610
- if (this.armSession === null || this.session !== this.armSession) return false;
611
- if (this.boundSessionId !== null) {
612
- const liveId = typeof this.session?.id === 'string' ? this.session.id : null;
613
- if (liveId !== this.boundSessionId) return false;
614
- }
615
- const probe = typeof this.resolveCall === 'function' ? this.resolveCall : QUESTION_CALL_BINDING;
616
- let found;
617
- try {
618
- found = probe({
619
- session: this.session,
620
- agent: this.agent,
621
- declaredCallId: pending.call.callId,
622
- toolName: 'ask_user_question',
623
- });
624
- } catch {
625
- return false;
626
- }
627
- if (found === null || typeof found !== 'object' || found.ok !== true) return false;
628
- if (found.callId !== pending.call.callId) return false;
629
- // The SAME log record and the SAME turn, not merely the same id: a replayed id in a new
630
- // turn is a separate call.
631
- if (found.seq !== pending.call.seq) return false;
632
- const boundTurn = pending.call.turn;
633
- if ((found.turn ?? null) !== (boundTurn ?? null)) return false;
634
- return true;
635
- }
636
-
637
- /**
638
- * Build the pending record for one accepted question set.
639
- * @param {object[]} questions - projected questions.
640
- * @param {object} call - the verified native call.
641
- * @returns {object} pending record.
642
- */
643
- createPending(questions, call) {
644
- this.sequence += 1;
645
- const createdAt = this.now();
646
- const pending = {
647
- requestId: `question-${this.taskId}-${this.sequence}`,
648
- taskId: this.taskId,
649
- connectionId: this.connectionId,
650
- sessionId: this.boundSessionId,
651
- callId: call.callId,
652
- call,
653
- questions,
654
- createdAt,
655
- // FINITE by construction: a question pauses the execution budget, so an unbounded
656
- // wait would let a run hang forever on a commander that never answers.
657
- deadlineAt: createdAt + this.timeoutMs,
658
- state: QUESTION_STATES.pending,
659
- answer: null,
660
- answeredAt: null,
661
- settledAt: null,
662
- resolvedWith: null,
663
- resolve: null,
664
- reject: null,
665
- timer: null,
666
- onAbort: null,
667
- externalSignal: null,
668
- };
669
- this.pending = pending;
670
- return pending;
671
- }
672
-
673
- /** Publish one pending question set; an observer throw is contained. */
674
- emitPending(pending) {
675
- if (this.onPending === null) return;
676
- try {
677
- this.onPending(this.publicView(pending));
678
- } catch (error) {
679
- this.logger?.warn?.('dsh-delegate: question observer failed', String(error?.code ?? ''));
680
- }
681
- }
682
-
683
- /**
684
- * Wait, boundedly, for the commander's answer.
685
- * @param {object} pending - pending record.
686
- * @param {AbortSignal | null} signal - the asking tool's cancellation.
687
- * @returns {Promise<{ answers: object[] }>} the answer.
688
- */
689
- async waitForAnswer(pending, signal) {
690
- const settled = new Promise((resolvePromise, rejectPromise) => {
691
- pending.resolve = resolvePromise;
692
- pending.reject = rejectPromise;
693
- });
694
- pending.timer = setTimeout(() => {
695
- pending.timer = null;
696
- this.settle(pending, QUESTION_STATES.expired, QUESTION_REASONS.expired);
697
- }, Math.max(0, pending.deadlineAt - this.now()));
698
- pending.timer.unref?.();
699
- if (signal !== null && typeof signal.addEventListener === 'function') {
700
- pending.externalSignal = signal;
701
- pending.onAbort = () => {
702
- this.settle(pending, QUESTION_STATES.cancelled, QUESTION_REASONS.cancelled);
703
- };
704
- signal.addEventListener('abort', pending.onAbort, { once: true });
705
- }
706
- this.emitPending(pending);
707
- try {
708
- return await settled;
709
- } finally {
710
- this.clearPending(pending);
711
- }
712
- }
713
-
714
- /**
715
- * Apply one answer to the LIVE pending question set.
716
- *
717
- * The bound native call is re-checked FIRST: an answer must never be replayed onto a
718
- * call that has already returned, been replaced, or whose turn has closed.
719
- * @param {object} request - `requestId`, `answers`.
720
- * @returns {{ requestId: string, taskId: string, callId: string, answers: object[], answeredAt: number }} receipt.
721
- * @throws {QuestionError} when no live set matches, the call is gone, or the answers are invalid.
722
- */
723
- decide(request) {
724
- const requestId = typeof request?.requestId === 'string' ? request.requestId : '';
725
- if (requestId === '') {
726
- throw new QuestionError(QUESTION_CODES.questionNotFound, 'requestId is required', { field: 'requestId' });
727
- }
728
- const pending = this.pending;
729
- if (pending === null || pending.requestId !== requestId) {
730
- const settled = this.history.find((entry) => entry.requestId === requestId) ?? null;
731
- if (settled !== null) {
732
- throw new QuestionError(QUESTION_CODES.alreadyAnswered, QUESTION_REASONS.alreadyAnswered, {
733
- requestId,
734
- state: settled.state,
735
- });
736
- }
737
- throw new QuestionError(QUESTION_CODES.notPending, QUESTION_REASONS.notArmed, { requestId });
738
- }
739
- if (pending.state !== QUESTION_STATES.pending) {
740
- throw new QuestionError(QUESTION_CODES.alreadyAnswered, QUESTION_REASONS.alreadyAnswered, {
741
- requestId,
742
- state: pending.state,
743
- });
744
- }
745
- if (this.now() >= pending.deadlineAt) {
746
- this.settle(pending, QUESTION_STATES.expired, QUESTION_REASONS.expired);
747
- throw new QuestionError(QUESTION_CODES.expired, QUESTION_REASONS.expired, { requestId });
748
- }
749
- if (!this.callStillLive(pending)) {
750
- // The call this question belongs to is gone, so an answer would resume nothing (or
751
- // the wrong thing). Refused, and the set is closed rather than left answerable.
752
- this.settle(pending, QUESTION_STATES.refused, QUESTION_REASONS.callGone);
753
- throw new QuestionError(QUESTION_CODES.callGone, QUESTION_REASONS.callGone, {
754
- requestId,
755
- callId: pending.callId,
756
- });
757
- }
758
- const verdict = validateAnswers(pending.questions, request?.answers);
759
- if (verdict.ok !== true) {
760
- throw new QuestionError(QUESTION_CODES.answerInvalid, verdict.detail, {
761
- requestId,
762
- reason: verdict.reason,
763
- detail: verdict.detail,
764
- });
765
- }
766
- const answeredAt = this.now();
767
- this.settle(pending, QUESTION_STATES.answered, null, { answer: verdict.answers, answeredAt });
768
- return { requestId, taskId: pending.taskId, callId: pending.callId, answers: verdict.answers, answeredAt };
769
- }
770
-
771
- /** Settle one pending set exactly once and release its waiter. */
772
- settle(pending, state, reason, extra = {}) {
773
- if (pending.state !== QUESTION_STATES.pending) return;
774
- pending.state = state;
775
- pending.settledAt = this.now();
776
- if (reason !== null) pending.resolvedWith = reason;
777
- if (Array.isArray(extra.answer)) {
778
- pending.answer = extra.answer;
779
- pending.answeredAt = extra.answeredAt ?? pending.settledAt;
780
- }
781
- this.clearPending(pending);
782
- const entry = this.settledView(pending);
783
- this.history.push(entry);
784
- if (this.history.length > QuestionBridge.HISTORY_BOUND) this.history.shift();
785
- const resolve = pending.resolve;
786
- const reject = pending.reject;
787
- if (resolve !== null || reject !== null) {
788
- if (state === QUESTION_STATES.answered) {
789
- resolve?.({ answers: pending.answer });
790
- } else {
791
- reject?.(nativeRefusal(state, reason));
792
- }
793
- }
794
- try {
795
- this.onSettled?.(entry);
796
- } catch (error) {
797
- this.logger?.warn?.('dsh-delegate: question settled observer failed', String(error?.code ?? ''));
798
- }
799
- }
800
-
801
- /** Drop the pending pointer and every timer/listener it owned. */
802
- clearPending(pending) {
803
- if (pending.timer !== null) {
804
- clearTimeout(pending.timer);
805
- pending.timer = null;
806
- }
807
- if (pending.externalSignal !== null && pending.onAbort !== null) {
808
- try {
809
- pending.externalSignal.removeEventListener?.('abort', pending.onAbort);
810
- } catch {
811
- // Removing a listener is best effort; the signal is external.
812
- }
813
- }
814
- pending.externalSignal = null;
815
- pending.onAbort = null;
816
- if (this.pending === pending) this.pending = null;
817
- }
818
-
819
- /** Settle whatever is pending, then refuse every later request. */
820
- stop(reason = QUESTION_REASONS.stop) {
821
- const pending = this.pending;
822
- if (pending !== null) this.settle(pending, QUESTION_STATES.cancelled, reason);
823
- this.armed = false;
824
- }
825
-
826
- /** Release everything. Idempotent. */
827
- dispose() {
828
- if (this.disposed) return;
829
- this.stop(QUESTION_REASONS.dispose);
830
- this.disposed = true;
831
- this.armed = false;
832
- this.agent = null;
833
- this.session = null;
834
- }
835
-
836
- /** The public projection of the current pending set, or null. */
837
- pendingView(pending = this.pending) {
838
- if (pending === null || pending === undefined) return null;
839
- if (pending.state !== QUESTION_STATES.pending) return null;
840
- return this.publicView(pending);
841
- }
842
-
843
- /**
844
- * Project one pending record for the commander.
845
- *
846
- * The questions are published EXACTLY as accepted — this is the same set whose
847
- * serialised size was checked, so nothing here can shorten them.
848
- */
849
- publicView(pending) {
850
- return {
851
- requestId: pending.requestId,
852
- taskId: pending.taskId,
853
- sessionId: pending.sessionId,
854
- callId: pending.callId,
855
- state: QUESTION_STATES.pending,
856
- createdAt: pending.createdAt,
857
- deadlineAt: pending.deadlineAt,
858
- questions: pending.questions.map((question) => ({
859
- id: question.id,
860
- question: question.question,
861
- header: question.header,
862
- detail: question.detail,
863
- options: question.options.map((option) => ({ label: option.label, description: option.description })),
864
- multiSelect: question.multiSelect,
865
- intent: question.intent,
866
- })),
867
- grantsAccess: false,
868
- };
869
- }
870
-
871
- /** Project one settled set as evidence. */
872
- settledView(pending) {
873
- return {
874
- requestId: pending.requestId,
875
- taskId: pending.taskId,
876
- callId: pending.callId,
877
- state: pending.state,
878
- questions: pending.questions.map((question) => ({ id: question.id, question: question.question })),
879
- answers: pending.answer === null ? null : pending.answer.map((answer) => ({
880
- id: answer.id,
881
- selected: [...answer.selected],
882
- ...(answer.custom === undefined ? {} : { custom: answer.custom }),
883
- })),
884
- reason: pending.resolvedWith,
885
- createdAt: pending.createdAt,
886
- settledAt: pending.settledAt,
887
- answeredAt: pending.answeredAt,
888
- };
889
- }
890
-
891
- historyView() {
892
- return this.history.map((entry) => entry);
893
- }
894
- }
895
-
896
- /**
897
- * The refusal the asking tool receives when a question cannot be answered: shaped like the
898
- * native `UserQuestionError` so the tool result reads like any other native refusal.
899
- */
900
- function nativeRefusal(state, reason) {
901
- const code = state === QUESTION_STATES.expired ? 'ASK_TIMED_OUT' : 'ASK_ABORTED';
902
- const message = reason ?? (state === QUESTION_STATES.expired
903
- ? 'ask_user_question timed out before the commander answered'
904
- : 'ask_user_question was withdrawn before the commander answered');
905
- const error = new Error(message);
906
- error.name = 'UserQuestionError';
907
- error.code = code;
908
- return error;
909
- }
1
+ // The per-run QUESTION bridge: ordinary `ask_user_question` calls from a delegated
2
+ // worker, surfaced to the commander as a decision it can actually answer.
3
+ //
4
+ // The native seam is the Agent-scoped Cordis waterfall `'user-questions/request'`
5
+ // (`@deepseek-ai/dsh-user-questions`):
6
+ //
7
+ // request = { questions: [{ id, question, header?, detail?, options?, multiSelect?,
8
+ // intent? }], agent?, signal?, wait?: { callId, timed? } }
9
+ // → { answers: [{ id, selected: string[], custom?: string }] }
10
+ //
11
+ // A question is NOT an approval: an `approval` intent is refused here so the permission
12
+ // bridge stays the only channel that can grant anything.
13
+ //
14
+ // Two properties carry most of the design:
15
+ //
16
+ // * **The question is published WHOLE or refused.** A question set is only accepted if
17
+ // its exact serialised form fits {@link QUESTION_BOUNDS.wireChars}, so no later layer
18
+ // can shorten a question the commander is told it may answer. A set that cannot be
19
+ // published intact is refused at once, with a code the worker can act on.
20
+ // * **An answer is bound to a REAL native tool call.** The call id comes from the
21
+ // request, is verified against the Session log, and is re-checked before the answer is
22
+ // applied, so an answer can never be delivered to an expired or replaced call.
23
+
24
+ import { QUESTION_CALL_BINDING } from './question-call.js';
25
+ import { redactDeep } from '../config/redact.js';
26
+
27
+ /** What one question answerer may do, as a closed vocabulary. */
28
+ export const QUESTION_CODES = Object.freeze({
29
+ unbound: 'QUESTION_UNBOUND',
30
+ busy: 'QUESTION_BUSY',
31
+ approvalIntent: 'QUESTION_APPROVAL_INTENT',
32
+ answerInvalid: 'QUESTION_ANSWER_INVALID',
33
+ questionNotFound: 'QUESTION_QUESTION_NOT_FOUND',
34
+ questionSettled: 'QUESTION_QUESTION_SETTLED',
35
+ notPending: 'QUESTION_NOT_PENDING',
36
+ alreadyAnswered: 'QUESTION_ALREADY_ANSWERED',
37
+ expired: 'QUESTION_EXPIRED',
38
+ // The question set cannot be published whole, so it is refused instead of being shown
39
+ // shortened. `QUESTION_PAYLOAD_TOO_LARGE` names the size bound explicitly.
40
+ payloadTooLarge: 'QUESTION_PAYLOAD_TOO_LARGE',
41
+ redacted: 'QUESTION_PAYLOAD_REDACTED',
42
+ // The question's own identity (id) is missing, too long or duplicated.
43
+ badIdentity: 'QUESTION_IDENTITY_INVALID',
44
+ // No trustworthy native tool call could be bound to this question.
45
+ noCall: 'QUESTION_CALL_UNVERIFIED',
46
+ // The bound call is no longer live, so an answer must not be replayed onto it.
47
+ callGone: 'QUESTION_CALL_GONE',
48
+ });
49
+
50
+ /** Where a pending question set puts the task. */
51
+ export const QUESTION_PHASE = Object.freeze({
52
+ pending: 'awaiting-question',
53
+ });
54
+
55
+ /** Fixed refusal reasons, stable machine strings the commander sees verbatim. */
56
+ export const QUESTION_REASONS = Object.freeze({
57
+ notArmed: 'the question bridge is not armed for this run',
58
+ disposed: 'the question bridge was disposed, so no answer can be applied',
59
+ foreignAgent: 'the question belongs to a different agent',
60
+ busy: 'another question set is already pending for this run',
61
+ approvalIntent: 'a question that presents an approval cannot be answered through the question channel',
62
+ badBatch: 'the answer batch must name each asked question exactly once',
63
+ unknownQuestion: 'the answer names a question that was not asked',
64
+ unknownOption: 'the answer selects an option the question did not offer',
65
+ tooManySelected: 'a single-select question takes exactly one option',
66
+ noSelection: 'an answer must select an option or carry custom text',
67
+ emptyCustom: 'custom text must be a non-empty string',
68
+ longCustom: 'custom text exceeds the bound',
69
+ expired: 'the question reached its deadline without an answer',
70
+ cancelled: 'the asking tool withdrew the question',
71
+ stop: 'the run stopped while the question was pending',
72
+ dispose: 'the plugin was disposed while the question was pending',
73
+ settled: 'the question set already settled',
74
+ alreadyAnswered: 'this question set was already answered; an answer applies once',
75
+ noQuestions: 'a question request carried no questions',
76
+ tooManyQuestions: 'a question request carried more questions than this channel accepts',
77
+ payloadTooLarge: 'the question set is too large to publish whole, so it cannot be answered here',
78
+ badId: 'a question id is missing, empty, too long or duplicated',
79
+ noCall: 'no native tool call could be bound to this question, so it cannot be answered here',
80
+ callGone: 'the bound native tool call is no longer live',
81
+ });
82
+
83
+ /**
84
+ * Default life of one pending question.
85
+ *
86
+ * Reusing the approval request's ten-minute default keeps ONE operator-facing number, and
87
+ * it is finite on purpose: a question pauses the execution budget, so an unbounded wait
88
+ * would let a run hang forever on a commander that never answers.
89
+ */
90
+ export const QUESTION_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
91
+ /** Ceiling on a configured question life. */
92
+ export const QUESTION_MAX_TIMEOUT_MS = 30 * 60 * 1000;
93
+
94
+ /**
95
+ * Bounds on one question set and one answer.
96
+ *
97
+ * `wireChars` is the important one: it is a budget on the EXACT JSON the commander will
98
+ * be sent, escapes included. It is set well below the MCP tool-text bound (20 000) so the
99
+ * question block, the receiving answer's other fields and a decision receipt can always
100
+ * travel together. A set that does not fit is refused, never published shortened.
101
+ */
102
+ export const QUESTION_BOUNDS = Object.freeze({
103
+ /** Maximum questions in one request. */
104
+ questions: 24,
105
+ /** Maximum options offered by one question. */
106
+ options: 24,
107
+ /** Maximum characters for a question's own text. */
108
+ questionChars: 2_000,
109
+ /** Maximum characters for a question's detail. */
110
+ detailChars: 8_000,
111
+ /** Maximum characters for a header. */
112
+ headerChars: 200,
113
+ /** Maximum characters for one option label. */
114
+ optionLabelChars: 400,
115
+ /** Maximum characters for one option description. */
116
+ optionDescriptionChars: 1_000,
117
+ /** Maximum characters accepted as a custom answer. */
118
+ customChars: 4_000,
119
+ /** Maximum characters for a question id. */
120
+ idChars: 200,
121
+ /**
122
+ * Maximum characters of the exact serialised question block.
123
+ *
124
+ * Deliberately conservative: a wait answer also carries the task summary, routing and
125
+ * metrics, and an answer receipt must fit beside a live question. 12 000 leaves that
126
+ * room and is still far above any question a worker should ask.
127
+ */
128
+ wireChars: 12_000,
129
+ });
130
+
131
+ export const QUESTION_STATES = Object.freeze({
132
+ pending: 'pending',
133
+ answered: 'answered',
134
+ expired: 'expired',
135
+ cancelled: 'cancelled',
136
+ refused: 'refused',
137
+ });
138
+
139
+ /** Raised for every refusal of the answer verb. `details` is bounded and secret-free. */
140
+ export class QuestionError extends Error {
141
+ /**
142
+ * @param {string} code - stable machine code.
143
+ * @param {string} message - operator-facing explanation.
144
+ * @param {object} [details] - bounded, non-secret context.
145
+ */
146
+ constructor(code, message, details = {}) {
147
+ super(message);
148
+ this.name = 'QuestionError';
149
+ this.code = code;
150
+ this.details = details;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * A copy of one question, exactly as the commander will be shown it.
156
+ *
157
+ * The id is used VERBATIM: it is the value the answer must quote and the value the native
158
+ * answerer echoes, so trimming it or inventing one would break the binding. A question
159
+ * with no usable id is refused by the caller.
160
+ * @param {unknown} question - one native question item.
161
+ * @returns {{ id: string, question: string, header: string | null, detail: string | null,
162
+ * options: { label: string, description: string | null }[], multiSelect: boolean,
163
+ * intent: string | null } | null} the projection, or null when unusable.
164
+ */
165
+ export function projectQuestion(question) {
166
+ if (question === null || typeof question !== 'object' || Array.isArray(question)) return null;
167
+ if (typeof question.id !== 'string' || question.id === '') return null;
168
+ const text = typeof question.question === 'string' ? question.question : '';
169
+ if (text.trim() === '') return null;
170
+ const options = [];
171
+ if (Array.isArray(question.options)) {
172
+ for (const option of question.options) {
173
+ if (option === null || typeof option !== 'object') return null;
174
+ const label = typeof option.label === 'string' ? option.label : '';
175
+ if (label === '') return null;
176
+ options.push({
177
+ label,
178
+ description: typeof option.description === 'string' && option.description !== ''
179
+ ? option.description
180
+ : null,
181
+ });
182
+ }
183
+ }
184
+ const intent = question.intent !== null && typeof question.intent === 'object'
185
+ && typeof question.intent.kind === 'string'
186
+ ? question.intent.kind
187
+ : null;
188
+ return {
189
+ id: question.id,
190
+ question: text,
191
+ header: typeof question.header === 'string' && question.header !== '' ? question.header : null,
192
+ detail: typeof question.detail === 'string' && question.detail !== '' ? question.detail : null,
193
+ options,
194
+ multiSelect: question.multiSelect === true,
195
+ intent,
196
+ };
197
+ }
198
+
199
+ /**
200
+ * The EXACT serialised form of a question set, as the commander receives it.
201
+ *
202
+ * Measured with `JSON.stringify`, so quotes, backslashes and other escapes count at their
203
+ * real serialised width — a set whose text is 11 000 raw characters but 22 000 escaped
204
+ * characters does NOT fit, and measuring `length` field by field would have missed it.
205
+ * @param {object[]} questions - projected questions.
206
+ * @returns {number} serialised length in UTF-16 units.
207
+ */
208
+ export function questionWireLength(questions) {
209
+ return JSON.stringify(questions).length;
210
+ }
211
+
212
+ /**
213
+ * Whether one projected question set fits every bound, measured on the real wire form.
214
+ *
215
+ * Returned as a fact rather than logged: a set that does not fit must be REFUSED, because
216
+ * publishing it shortened would show the commander a question the worker never asked and
217
+ * apply its answer to a call that expected something else.
218
+ * @param {object[]} questions - projected questions.
219
+ * @returns {{ ok: true } | { ok: false, code: string, reason: string, detail: string }} verdict.
220
+ */
221
+ export function questionsFit(questions) {
222
+ if (!Array.isArray(questions) || questions.length === 0) {
223
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.noQuestions, detail: 'no questions were asked' };
224
+ }
225
+ if (questions.length > QUESTION_BOUNDS.questions) {
226
+ return {
227
+ ok: false,
228
+ code: QUESTION_CODES.answerInvalid,
229
+ reason: QUESTION_REASONS.tooManyQuestions,
230
+ detail: `${questions.length} questions exceed the bound of ${QUESTION_BOUNDS.questions}`,
231
+ };
232
+ }
233
+ const seen = new Set();
234
+ for (const question of questions) {
235
+ if (typeof question.id !== 'string' || question.id === '' || question.id.length > QUESTION_BOUNDS.idChars) {
236
+ return { ok: false, code: QUESTION_CODES.badIdentity, reason: QUESTION_REASONS.badId, detail: 'a question id is missing or too long' };
237
+ }
238
+ if (seen.has(question.id)) {
239
+ return { ok: false, code: QUESTION_CODES.badIdentity, reason: QUESTION_REASONS.badId, detail: `duplicate question id ${question.id}` };
240
+ }
241
+ seen.add(question.id);
242
+ if (question.question.length > QUESTION_BOUNDS.questionChars) {
243
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `question ${question.id} is too long` };
244
+ }
245
+ if (question.detail !== null && question.detail.length > QUESTION_BOUNDS.detailChars) {
246
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `detail of ${question.id} is too long` };
247
+ }
248
+ if (question.header !== null && question.header.length > QUESTION_BOUNDS.headerChars) {
249
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `header of ${question.id} is too long` };
250
+ }
251
+ if (question.options.length > QUESTION_BOUNDS.options) {
252
+ return {
253
+ ok: false,
254
+ code: QUESTION_CODES.answerInvalid,
255
+ reason: QUESTION_REASONS.badBatch,
256
+ detail: `${question.id} offers ${question.options.length} options, above the bound of ${QUESTION_BOUNDS.options}`,
257
+ };
258
+ }
259
+ const labels = new Set();
260
+ for (const option of question.options) {
261
+ if (option.label.length > QUESTION_BOUNDS.optionLabelChars) {
262
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `an option label of ${question.id} is too long` };
263
+ }
264
+ if (option.description !== null && option.description.length > QUESTION_BOUNDS.optionDescriptionChars) {
265
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `an option description of ${question.id} is too long` };
266
+ }
267
+ // Two options with one label make an answer ambiguous: the worker could not tell
268
+ // which one was chosen.
269
+ if (labels.has(option.label)) {
270
+ return { ok: false, code: QUESTION_CODES.answerInvalid, reason: QUESTION_REASONS.badBatch, detail: `${question.id} repeats the option label ${JSON.stringify(option.label)}` };
271
+ }
272
+ labels.add(option.label);
273
+ }
274
+ }
275
+ const wire = questionWireLength(questions);
276
+ if (wire > QUESTION_BOUNDS.wireChars) {
277
+ return {
278
+ ok: false,
279
+ code: QUESTION_CODES.payloadTooLarge,
280
+ reason: QUESTION_REASONS.payloadTooLarge,
281
+ detail: `the question set serialises to ${wire} characters, above the publishable bound of ${QUESTION_BOUNDS.wireChars}`,
282
+ wireChars: wire,
283
+ limit: QUESTION_BOUNDS.wireChars,
284
+ };
285
+ }
286
+ return { ok: true, wireChars: wire };
287
+ }
288
+
289
+ /**
290
+ * Validate one answer batch against the questions that were ACTUALLY asked.
291
+ *
292
+ * A single-select question may carry BOTH a selection and custom text: the native tool
293
+ * documents `selected` as allowed to accompany custom text, and the UI shows "Other"
294
+ * beside the list. Only a multi-selection is refused there.
295
+ * @param {object[]} asked - the projected questions of the live request.
296
+ * @param {unknown} answers - the commander's proposed answers.
297
+ * @returns {{ ok: true, answers: { id: string, selected: string[], custom?: string }[] }
298
+ * | { ok: false, reason: string, detail: string }} verdict.
299
+ */
300
+ export function validateAnswers(asked, answers) {
301
+ if (!Array.isArray(answers)) {
302
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: 'answers must be an array' };
303
+ }
304
+ const byId = new Map(asked.map((question) => [question.id, question]));
305
+ // Membership and uniqueness across the WHOLE batch are checked FIRST, so a batch naming
306
+ // a question nobody asked reports exactly that rather than whatever option it mentioned.
307
+ const seenIds = new Set();
308
+ for (const answer of answers) {
309
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
310
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: 'each answer must be an object' };
311
+ }
312
+ const id = typeof answer.id === 'string' ? answer.id : '';
313
+ if (!byId.has(id)) {
314
+ return { ok: false, reason: QUESTION_REASONS.unknownQuestion, detail: `no question with id ${JSON.stringify(id)} was asked` };
315
+ }
316
+ if (seenIds.has(id)) {
317
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `question ${id} is answered more than once` };
318
+ }
319
+ seenIds.add(id);
320
+ }
321
+ if (seenIds.size !== asked.length || !asked.every((question) => seenIds.has(question.id))) {
322
+ return {
323
+ ok: false,
324
+ reason: QUESTION_REASONS.badBatch,
325
+ detail: `the batch must name each of the ${asked.length} questions exactly once`,
326
+ };
327
+ }
328
+ const normalized = [];
329
+ for (const answer of answers) {
330
+ const id = answer.id;
331
+ const question = byId.get(id);
332
+ const selected = answer.selected === undefined ? [] : answer.selected;
333
+ if (!Array.isArray(selected) || selected.some((label) => typeof label !== 'string')) {
334
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `selected of ${id} must be an array of labels` };
335
+ }
336
+ const labels = question.options.map((option) => option.label);
337
+ for (const label of selected) {
338
+ if (!labels.includes(label)) {
339
+ return { ok: false, reason: QUESTION_REASONS.unknownOption, detail: `${JSON.stringify(label)} is not an option of ${id}` };
340
+ }
341
+ }
342
+ if (new Set(selected).size !== selected.length) {
343
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `selected of ${id} repeats a label` };
344
+ }
345
+ let custom;
346
+ if (answer.custom !== undefined && answer.custom !== null) {
347
+ if (typeof answer.custom !== 'string') {
348
+ return { ok: false, reason: QUESTION_REASONS.badBatch, detail: `custom of ${id} must be a string` };
349
+ }
350
+ if (answer.custom.length > QUESTION_BOUNDS.customChars) {
351
+ return { ok: false, reason: QUESTION_REASONS.longCustom, detail: `custom of ${id} exceeds ${QUESTION_BOUNDS.customChars} characters` };
352
+ }
353
+ if (answer.custom.trim() === '') {
354
+ return { ok: false, reason: QUESTION_REASONS.emptyCustom, detail: `custom of ${id} is empty` };
355
+ }
356
+ custom = answer.custom;
357
+ }
358
+ if (question.multiSelect !== true && selected.length > 1) {
359
+ return { ok: false, reason: QUESTION_REASONS.tooManySelected, detail: `${id} is single-select and received ${selected.length} labels` };
360
+ }
361
+ if (selected.length === 0 && custom === undefined) {
362
+ return {
363
+ ok: false,
364
+ reason: QUESTION_REASONS.noSelection,
365
+ detail: question.options.length === 0
366
+ ? `${id} offers no options, so it needs custom text`
367
+ : `${id} carries neither a selection nor custom text`,
368
+ };
369
+ }
370
+ normalized.push({ id, selected: [...selected], ...(custom === undefined ? {} : { custom }) });
371
+ }
372
+ return { ok: true, answers: normalized };
373
+ }
374
+
375
+ /**
376
+ * One run's question bridge. Same shape as `PermissionBridge` on purpose: one Agent, one
377
+ * outstanding request, a bounded evidence trail, a lifecycle that releases the waiter.
378
+ */
379
+ export class QuestionBridge {
380
+ /**
381
+ * @param {object} options - `taskId`, optional `connectionId`, `timeoutMs`, `now`,
382
+ * `onPending`, `onSettled`, `logger`, `resolveCall` (the call-binding probe).
383
+ */
384
+ constructor(options) {
385
+ if (typeof options?.taskId !== 'string' || options.taskId === '') {
386
+ throw new TypeError('QuestionBridge needs the taskId it belongs to');
387
+ }
388
+ this.taskId = options.taskId;
389
+ this.connectionId = typeof options.connectionId === 'string' ? options.connectionId : null;
390
+ this.now = typeof options.now === 'function' ? options.now : () => Date.now();
391
+ const configured = Number(options.timeoutMs);
392
+ this.timeoutMs = Number.isFinite(configured) && configured > 0
393
+ ? Math.min(Math.trunc(configured), QUESTION_MAX_TIMEOUT_MS)
394
+ : QUESTION_DEFAULT_TIMEOUT_MS;
395
+ this.onPending = typeof options.onPending === 'function' ? options.onPending : null;
396
+ this.onSettled = typeof options.onSettled === 'function' ? options.onSettled : null;
397
+ this.logger = options.logger ?? null;
398
+ this.resolveCall = typeof options.resolveCall === 'function' ? options.resolveCall : null;
399
+ this.armed = false;
400
+ this.disposed = false;
401
+ this.agent = null;
402
+ this.session = null;
403
+ this.boundSessionId = null;
404
+ // The exact Agent/Session objects this bridge was armed with; a replaced object is a
405
+ // different conversation even when its id was recycled.
406
+ this.armAgent = null;
407
+ this.armSession = null;
408
+ this.pending = null;
409
+ this.history = [];
410
+ this.sequence = 0;
411
+ }
412
+
413
+ static get HISTORY_BOUND() {
414
+ return 8;
415
+ }
416
+
417
+ /**
418
+ * Bind the bridge to the Agent/Session it answers for.
419
+ * @param {object} agent - the live native Agent the run will drive.
420
+ * @returns {{ taskId: string, sessionId: string }} what was armed.
421
+ * @throws {QuestionError} when the agent is unusable or is not the bound one.
422
+ */
423
+ arm(agent) {
424
+ if (this.disposed) {
425
+ throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.disposed);
426
+ }
427
+ const session = agent?.session ?? null;
428
+ const sessionId = typeof session?.id === 'string' ? session.id : null;
429
+ if (session === null || sessionId === null) {
430
+ throw new QuestionError(QUESTION_CODES.unbound, 'the delegated agent exposes no session to bind questions to', {
431
+ reason: 'no session',
432
+ });
433
+ }
434
+ if (this.agent !== null && this.agent !== agent) {
435
+ throw new QuestionError(QUESTION_CODES.unbound, 'the question bridge is already bound to another agent', {
436
+ reason: 'agent mismatch',
437
+ });
438
+ }
439
+ if (this.session !== null && this.session !== session) {
440
+ throw new QuestionError(QUESTION_CODES.unbound, 'the question bridge is already bound to another session');
441
+ }
442
+ this.agent = agent;
443
+ this.session = session;
444
+ this.boundSessionId = sessionId;
445
+ // The EXACT objects this bridge was armed with. `arm()` may be called again for the same
446
+ // Agent (it is idempotent), but a replaced Agent or Session must be detectable, which is a
447
+ // question of object identity rather than of ids.
448
+ this.armAgent = agent;
449
+ this.armSession = session;
450
+ this.armed = true;
451
+ return { taskId: this.taskId, sessionId };
452
+ }
453
+
454
+ /**
455
+ * Whether this bridge answers one native question request: the EXACT live Agent object
456
+ * and the same Session, because the seam passes the live Agent and object identity
457
+ * cannot be forged from data.
458
+ * @param {object} request - native question request.
459
+ * @returns {boolean} true when this bridge owns the request.
460
+ */
461
+ owns(request) {
462
+ if (this.armed !== true || this.disposed === true) return false;
463
+ if (this.agent === null || this.session === null) return false;
464
+ const agent = request?.agent;
465
+ if (agent === null || agent === undefined || typeof agent !== 'object') return false;
466
+ const session = agent.session;
467
+ if (session === null || session === undefined || typeof session !== 'object') return false;
468
+ if (agent !== this.agent) return false;
469
+ if (session !== this.session) return false;
470
+ if (this.boundSessionId !== null && typeof session.id === 'string' && session.id !== this.boundSessionId) return false;
471
+ return true;
472
+ }
473
+
474
+ /** Whether any question of a set presents an approval decision. */
475
+ static presentsApproval(questions) {
476
+ return questions.some((question) => question.intent === 'approval');
477
+ }
478
+
479
+ /**
480
+ * Answer one native question request.
481
+ * @param {object} request - native question request.
482
+ * @returns {Promise<{ answers: object[] }>} the commander's answer.
483
+ * @throws {QuestionError} when this bridge cannot answer the request.
484
+ */
485
+ async answer(request) {
486
+ if (this.armed !== true || this.disposed === true) {
487
+ throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.notArmed);
488
+ }
489
+ if (!this.owns(request)) {
490
+ throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.foreignAgent);
491
+ }
492
+ if (this.pending !== null) {
493
+ throw new QuestionError(QUESTION_CODES.busy, QUESTION_REASONS.busy);
494
+ }
495
+ const raw = Array.isArray(request?.questions) ? request.questions : [];
496
+ const questions = [];
497
+ for (const item of raw) {
498
+ const projected = projectQuestion(item);
499
+ if (projected === null) {
500
+ throw new QuestionError(QUESTION_CODES.badIdentity, 'a question could not be described', {
501
+ reason: QUESTION_REASONS.badId,
502
+ detail: 'a question needs a non-empty string id and a non-empty question',
503
+ });
504
+ }
505
+ questions.push(projected);
506
+ }
507
+ const fit = questionsFit(questions);
508
+ if (fit.ok !== true) {
509
+ // Refused BEFORE anything is published: the commander is never offered a question
510
+ // set this channel cannot carry whole, so it can never be answered from a
511
+ // shortened copy.
512
+ throw new QuestionError(fit.code, 'the question set cannot be published whole', fit);
513
+ }
514
+ if (JSON.stringify(redactDeep(questions)) !== JSON.stringify(questions)) {
515
+ throw new QuestionError(QUESTION_CODES.redacted,
516
+ 'the question contains private data that cannot be published intact; rephrase it without private values');
517
+ }
518
+ if (QuestionBridge.presentsApproval(questions)) {
519
+ throw new QuestionError(QUESTION_CODES.approvalIntent, QUESTION_REASONS.approvalIntent, {
520
+ reason: QUESTION_REASONS.approvalIntent,
521
+ channel: 'permission',
522
+ hint: 'request the exact tool call through the approval channel; a question cannot grant access',
523
+ });
524
+ }
525
+ const bound = await this.bindCall(request);
526
+ if (bound.ok !== true) {
527
+ throw new QuestionError(bound.code, 'no live native tool call could be bound to this question', {
528
+ reason: bound.reason,
529
+ detail: bound.detail,
530
+ });
531
+ }
532
+ if (!this.owns(request)) {
533
+ throw new QuestionError(QUESTION_CODES.unbound, QUESTION_REASONS.foreignAgent);
534
+ }
535
+ if (this.pending !== null) {
536
+ throw new QuestionError(QUESTION_CODES.busy, QUESTION_REASONS.busy);
537
+ }
538
+ const signal = request?.signal ?? null;
539
+ if (signal?.aborted === true) {
540
+ throw new QuestionError(QUESTION_CODES.questionSettled, QUESTION_REASONS.cancelled);
541
+ }
542
+ const pending = this.createPending(questions, bound.call);
543
+ return await this.waitForAnswer(pending, signal);
544
+ }
545
+
546
+ /**
547
+ * Bind this question to the ONE native `ask_user_question` call that is executing it.
548
+ *
549
+ * The call id is taken from the request (`wait.callId`, which the native tool sets) and
550
+ * then VERIFIED against the Session log by {@link QUESTION_CALL_BINDING}: exactly one
551
+ * matching `tool/call` in the open turn, no recorded result for it, owned by this Agent.
552
+ * A question that cannot be bound this way is refused rather than answered against a
553
+ * guess — delivering an answer to the wrong call would resume an operation nobody asked
554
+ * about.
555
+ * @param {object} request - native question request.
556
+ * @returns {Promise<{ ok: true, call: object } | { ok: false, code: string, reason: string, detail: string }>} binding.
557
+ */
558
+ async bindCall(request) {
559
+ const declared = typeof request?.wait?.callId === 'string' ? request.wait.callId : '';
560
+ const probe = typeof this.resolveCall === 'function' ? this.resolveCall : QUESTION_CALL_BINDING;
561
+ let found;
562
+ try {
563
+ found = probe({
564
+ session: this.session,
565
+ agent: this.agent,
566
+ declaredCallId: declared === '' ? null : declared,
567
+ toolName: 'ask_user_question',
568
+ });
569
+ } catch (error) {
570
+ return {
571
+ ok: false,
572
+ code: QUESTION_CODES.noCall,
573
+ reason: QUESTION_REASONS.noCall,
574
+ detail: `the call binding could not be read (${String(error?.code ?? 'error')})`,
575
+ };
576
+ }
577
+ if (found === null || typeof found !== 'object' || found.ok !== true) {
578
+ return {
579
+ ok: false,
580
+ code: QUESTION_CODES.noCall,
581
+ reason: QUESTION_REASONS.noCall,
582
+ detail: typeof found?.detail === 'string' ? found.detail : 'no unique open tool call matches this question',
583
+ };
584
+ }
585
+ return {
586
+ ok: true,
587
+ call: { callId: found.callId, seq: found.seq, turn: found.turn ?? null },
588
+ };
589
+ }
590
+
591
+ /**
592
+ * Whether the bound call is still the live one this answer may resume.
593
+ *
594
+ * An id match alone is NOT enough, and the reproduction proved it: after
595
+ * `turn/end, turn/start(turn2), tool/call c turn2` the same id `c` is a DIFFERENT call in a
596
+ * different turn, so an answer bound to the first one would be delivered to an operation
597
+ * that never asked. Nor is it enough that the bridge still holds *a* session: a replaced
598
+ * Session object is a different conversation even when its id was recycled.
599
+ *
600
+ * So four facts must ALL still hold: the same Agent object, the same Session object, the
601
+ * same Session id, and the same call at the same log offset in the same turn.
602
+ * @param {object} pending - pending record.
603
+ * @returns {boolean} true when the call is still live and still the same call.
604
+ */
605
+ callStillLive(pending) {
606
+ if (pending?.call === null || pending?.call === undefined) return false;
607
+ if (!this.owns({ agent: this.agent })) return false;
608
+ // The Agent and the Session must still be the objects this bridge was armed with.
609
+ if (this.armAgent === null || this.agent !== this.armAgent) return false;
610
+ if (this.armSession === null || this.session !== this.armSession) return false;
611
+ if (this.boundSessionId !== null) {
612
+ const liveId = typeof this.session?.id === 'string' ? this.session.id : null;
613
+ if (liveId !== this.boundSessionId) return false;
614
+ }
615
+ const probe = typeof this.resolveCall === 'function' ? this.resolveCall : QUESTION_CALL_BINDING;
616
+ let found;
617
+ try {
618
+ found = probe({
619
+ session: this.session,
620
+ agent: this.agent,
621
+ declaredCallId: pending.call.callId,
622
+ toolName: 'ask_user_question',
623
+ });
624
+ } catch {
625
+ return false;
626
+ }
627
+ if (found === null || typeof found !== 'object' || found.ok !== true) return false;
628
+ if (found.callId !== pending.call.callId) return false;
629
+ // The SAME log record and the SAME turn, not merely the same id: a replayed id in a new
630
+ // turn is a separate call.
631
+ if (found.seq !== pending.call.seq) return false;
632
+ const boundTurn = pending.call.turn;
633
+ if ((found.turn ?? null) !== (boundTurn ?? null)) return false;
634
+ return true;
635
+ }
636
+
637
+ /**
638
+ * Build the pending record for one accepted question set.
639
+ * @param {object[]} questions - projected questions.
640
+ * @param {object} call - the verified native call.
641
+ * @returns {object} pending record.
642
+ */
643
+ createPending(questions, call) {
644
+ this.sequence += 1;
645
+ const createdAt = this.now();
646
+ const pending = {
647
+ requestId: `question-${this.taskId}-${this.sequence}`,
648
+ taskId: this.taskId,
649
+ connectionId: this.connectionId,
650
+ sessionId: this.boundSessionId,
651
+ callId: call.callId,
652
+ call,
653
+ questions,
654
+ createdAt,
655
+ // FINITE by construction: a question pauses the execution budget, so an unbounded
656
+ // wait would let a run hang forever on a commander that never answers.
657
+ deadlineAt: createdAt + this.timeoutMs,
658
+ state: QUESTION_STATES.pending,
659
+ answer: null,
660
+ answeredAt: null,
661
+ settledAt: null,
662
+ resolvedWith: null,
663
+ resolve: null,
664
+ reject: null,
665
+ timer: null,
666
+ onAbort: null,
667
+ externalSignal: null,
668
+ };
669
+ this.pending = pending;
670
+ return pending;
671
+ }
672
+
673
+ /** Publish one pending question set; an observer throw is contained. */
674
+ emitPending(pending) {
675
+ if (this.onPending === null) return;
676
+ try {
677
+ this.onPending(this.publicView(pending));
678
+ } catch (error) {
679
+ this.logger?.warn?.('dsh-delegate: question observer failed', String(error?.code ?? ''));
680
+ }
681
+ }
682
+
683
+ /**
684
+ * Wait, boundedly, for the commander's answer.
685
+ * @param {object} pending - pending record.
686
+ * @param {AbortSignal | null} signal - the asking tool's cancellation.
687
+ * @returns {Promise<{ answers: object[] }>} the answer.
688
+ */
689
+ async waitForAnswer(pending, signal) {
690
+ const settled = new Promise((resolvePromise, rejectPromise) => {
691
+ pending.resolve = resolvePromise;
692
+ pending.reject = rejectPromise;
693
+ });
694
+ pending.timer = setTimeout(() => {
695
+ pending.timer = null;
696
+ this.settle(pending, QUESTION_STATES.expired, QUESTION_REASONS.expired);
697
+ }, Math.max(0, pending.deadlineAt - this.now()));
698
+ pending.timer.unref?.();
699
+ if (signal !== null && typeof signal.addEventListener === 'function') {
700
+ pending.externalSignal = signal;
701
+ pending.onAbort = () => {
702
+ this.settle(pending, QUESTION_STATES.cancelled, QUESTION_REASONS.cancelled);
703
+ };
704
+ signal.addEventListener('abort', pending.onAbort, { once: true });
705
+ }
706
+ this.emitPending(pending);
707
+ try {
708
+ return await settled;
709
+ } finally {
710
+ this.clearPending(pending);
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Apply one answer to the LIVE pending question set.
716
+ *
717
+ * The bound native call is re-checked FIRST: an answer must never be replayed onto a
718
+ * call that has already returned, been replaced, or whose turn has closed.
719
+ * @param {object} request - `requestId`, `answers`.
720
+ * @returns {{ requestId: string, taskId: string, callId: string, answers: object[], answeredAt: number }} receipt.
721
+ * @throws {QuestionError} when no live set matches, the call is gone, or the answers are invalid.
722
+ */
723
+ decide(request) {
724
+ const requestId = typeof request?.requestId === 'string' ? request.requestId : '';
725
+ if (requestId === '') {
726
+ throw new QuestionError(QUESTION_CODES.questionNotFound, 'requestId is required', { field: 'requestId' });
727
+ }
728
+ const pending = this.pending;
729
+ if (pending === null || pending.requestId !== requestId) {
730
+ const settled = this.history.find((entry) => entry.requestId === requestId) ?? null;
731
+ if (settled !== null) {
732
+ throw new QuestionError(QUESTION_CODES.alreadyAnswered, QUESTION_REASONS.alreadyAnswered, {
733
+ requestId,
734
+ state: settled.state,
735
+ });
736
+ }
737
+ throw new QuestionError(QUESTION_CODES.notPending, QUESTION_REASONS.notArmed, { requestId });
738
+ }
739
+ if (pending.state !== QUESTION_STATES.pending) {
740
+ throw new QuestionError(QUESTION_CODES.alreadyAnswered, QUESTION_REASONS.alreadyAnswered, {
741
+ requestId,
742
+ state: pending.state,
743
+ });
744
+ }
745
+ if (this.now() >= pending.deadlineAt) {
746
+ this.settle(pending, QUESTION_STATES.expired, QUESTION_REASONS.expired);
747
+ throw new QuestionError(QUESTION_CODES.expired, QUESTION_REASONS.expired, { requestId });
748
+ }
749
+ if (!this.callStillLive(pending)) {
750
+ // The call this question belongs to is gone, so an answer would resume nothing (or
751
+ // the wrong thing). Refused, and the set is closed rather than left answerable.
752
+ this.settle(pending, QUESTION_STATES.refused, QUESTION_REASONS.callGone);
753
+ throw new QuestionError(QUESTION_CODES.callGone, QUESTION_REASONS.callGone, {
754
+ requestId,
755
+ callId: pending.callId,
756
+ });
757
+ }
758
+ const verdict = validateAnswers(pending.questions, request?.answers);
759
+ if (verdict.ok !== true) {
760
+ throw new QuestionError(QUESTION_CODES.answerInvalid, verdict.detail, {
761
+ requestId,
762
+ reason: verdict.reason,
763
+ detail: verdict.detail,
764
+ });
765
+ }
766
+ const answeredAt = this.now();
767
+ this.settle(pending, QUESTION_STATES.answered, null, { answer: verdict.answers, answeredAt });
768
+ return { requestId, taskId: pending.taskId, callId: pending.callId, answers: verdict.answers, answeredAt };
769
+ }
770
+
771
+ /** Settle one pending set exactly once and release its waiter. */
772
+ settle(pending, state, reason, extra = {}) {
773
+ if (pending.state !== QUESTION_STATES.pending) return;
774
+ pending.state = state;
775
+ pending.settledAt = this.now();
776
+ if (reason !== null) pending.resolvedWith = reason;
777
+ if (Array.isArray(extra.answer)) {
778
+ pending.answer = extra.answer;
779
+ pending.answeredAt = extra.answeredAt ?? pending.settledAt;
780
+ }
781
+ this.clearPending(pending);
782
+ const entry = this.settledView(pending);
783
+ this.history.push(entry);
784
+ if (this.history.length > QuestionBridge.HISTORY_BOUND) this.history.shift();
785
+ const resolve = pending.resolve;
786
+ const reject = pending.reject;
787
+ if (resolve !== null || reject !== null) {
788
+ if (state === QUESTION_STATES.answered) {
789
+ resolve?.({ answers: pending.answer });
790
+ } else {
791
+ reject?.(nativeRefusal(state, reason));
792
+ }
793
+ }
794
+ try {
795
+ this.onSettled?.(entry);
796
+ } catch (error) {
797
+ this.logger?.warn?.('dsh-delegate: question settled observer failed', String(error?.code ?? ''));
798
+ }
799
+ }
800
+
801
+ /** Drop the pending pointer and every timer/listener it owned. */
802
+ clearPending(pending) {
803
+ if (pending.timer !== null) {
804
+ clearTimeout(pending.timer);
805
+ pending.timer = null;
806
+ }
807
+ if (pending.externalSignal !== null && pending.onAbort !== null) {
808
+ try {
809
+ pending.externalSignal.removeEventListener?.('abort', pending.onAbort);
810
+ } catch {
811
+ // Removing a listener is best effort; the signal is external.
812
+ }
813
+ }
814
+ pending.externalSignal = null;
815
+ pending.onAbort = null;
816
+ if (this.pending === pending) this.pending = null;
817
+ }
818
+
819
+ /** Settle whatever is pending, then refuse every later request. */
820
+ stop(reason = QUESTION_REASONS.stop) {
821
+ const pending = this.pending;
822
+ if (pending !== null) this.settle(pending, QUESTION_STATES.cancelled, reason);
823
+ this.armed = false;
824
+ }
825
+
826
+ /** Release everything. Idempotent. */
827
+ dispose() {
828
+ if (this.disposed) return;
829
+ this.stop(QUESTION_REASONS.dispose);
830
+ this.disposed = true;
831
+ this.armed = false;
832
+ this.agent = null;
833
+ this.session = null;
834
+ }
835
+
836
+ /** The public projection of the current pending set, or null. */
837
+ pendingView(pending = this.pending) {
838
+ if (pending === null || pending === undefined) return null;
839
+ if (pending.state !== QUESTION_STATES.pending) return null;
840
+ return this.publicView(pending);
841
+ }
842
+
843
+ /**
844
+ * Project one pending record for the commander.
845
+ *
846
+ * The questions are published EXACTLY as accepted — this is the same set whose
847
+ * serialised size was checked, so nothing here can shorten them.
848
+ */
849
+ publicView(pending) {
850
+ return {
851
+ requestId: pending.requestId,
852
+ taskId: pending.taskId,
853
+ sessionId: pending.sessionId,
854
+ callId: pending.callId,
855
+ state: QUESTION_STATES.pending,
856
+ createdAt: pending.createdAt,
857
+ deadlineAt: pending.deadlineAt,
858
+ questions: pending.questions.map((question) => ({
859
+ id: question.id,
860
+ question: question.question,
861
+ header: question.header,
862
+ detail: question.detail,
863
+ options: question.options.map((option) => ({ label: option.label, description: option.description })),
864
+ multiSelect: question.multiSelect,
865
+ intent: question.intent,
866
+ })),
867
+ grantsAccess: false,
868
+ };
869
+ }
870
+
871
+ /** Project one settled set as evidence. */
872
+ settledView(pending) {
873
+ return {
874
+ requestId: pending.requestId,
875
+ taskId: pending.taskId,
876
+ callId: pending.callId,
877
+ state: pending.state,
878
+ questions: pending.questions.map((question) => ({ id: question.id, question: question.question })),
879
+ answers: pending.answer === null ? null : pending.answer.map((answer) => ({
880
+ id: answer.id,
881
+ selected: [...answer.selected],
882
+ ...(answer.custom === undefined ? {} : { custom: answer.custom }),
883
+ })),
884
+ reason: pending.resolvedWith,
885
+ createdAt: pending.createdAt,
886
+ settledAt: pending.settledAt,
887
+ answeredAt: pending.answeredAt,
888
+ };
889
+ }
890
+
891
+ historyView() {
892
+ return this.history.map((entry) => entry);
893
+ }
894
+ }
895
+
896
+ /**
897
+ * The refusal the asking tool receives when a question cannot be answered: shaped like the
898
+ * native `UserQuestionError` so the tool result reads like any other native refusal.
899
+ */
900
+ function nativeRefusal(state, reason) {
901
+ const code = state === QUESTION_STATES.expired ? 'ASK_TIMED_OUT' : 'ASK_ABORTED';
902
+ const message = reason ?? (state === QUESTION_STATES.expired
903
+ ? 'ask_user_question timed out before the commander answered'
904
+ : 'ask_user_question was withdrawn before the commander answered');
905
+ const error = new Error(message);
906
+ error.name = 'UserQuestionError';
907
+ error.code = code;
908
+ return error;
909
+ }