@thready-web/dsh-bot-plugin 0.1.0-beta.3 → 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,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
+ }
@@ -1,10 +1,16 @@
1
1
  /** Admission and host budgets. Neither function calls a model or reorders an inbox. */
2
2
  /**
3
- * Main-session caps. The main bot may do real work itself (bash, write, ...),
4
- * so the caps are a runaway guard, not a "dispatch first" policy. `main*` is
5
- * the cap after a dispatch or a host tool and is never looser than `chat*`;
6
- * set it lower in config to bring back the old "hand long work to a worker" squeeze.
3
+ * Main-session caps. The main bot may still call host tools; these caps are a
4
+ * runaway guard. Worker parallelism is a separate slot/queue policy: `perBot`
5
+ * and `global` limit running workers, and `perBotQueue` / `globalQueue` cap
6
+ * tickets waiting for a slot. `needs_user` does not occupy a running slot.
7
+ * `main*` is the cap after a dispatch or a host tool and is never looser than
8
+ * `chat*`.
7
9
  */
10
+ /** Hard ceiling so a typo cannot raise a slot cap without bound. */
11
+ export const WORK_SLOT_MAX = 64;
12
+ /** Hard ceiling so a typo cannot raise a queue cap without bound. */
13
+ export const WORK_QUEUE_MAX = 256;
8
14
  export const DEFAULT_WORK_BUDGET = Object.freeze({
9
15
  mainMaxSteps: 80,
10
16
  mainWallMs: 30 * 60 * 1000,
@@ -14,13 +20,35 @@ export const DEFAULT_WORK_BUDGET = Object.freeze({
14
20
  workerMaxSteps: 8,
15
21
  workerWallMs: 10 * 60 * 1000,
16
22
  workerMaxTokens: 400_000,
17
- perBot: 1,
18
- global: 2,
23
+ perBot: 2,
24
+ global: 4,
25
+ perBotQueue: 8,
26
+ globalQueue: 16,
19
27
  leaseMs: 60_000,
20
28
  starveMs: 30_000,
21
29
  mergeWindowMs: 1_000,
22
30
  });
23
31
  const BUDGET_KEYS = Object.keys(DEFAULT_WORK_BUDGET);
32
+ const INT_MAX = {
33
+ perBot: WORK_SLOT_MAX,
34
+ global: WORK_SLOT_MAX,
35
+ perBotQueue: WORK_QUEUE_MAX,
36
+ globalQueue: WORK_QUEUE_MAX,
37
+ };
38
+ /**
39
+ * A single bot cannot run more workers than the global cap, even if `perBot`
40
+ * is larger. The same applies to the queue caps. Existing running workers are
41
+ * not cancelled when a later process start uses a lower cap.
42
+ * @param {WorkBudget} budget
43
+ */
44
+ export function effectiveWorkLimits(budget) {
45
+ return {
46
+ perBot: Math.min(budget.perBot, budget.global),
47
+ global: budget.global,
48
+ perBotQueue: Math.min(budget.perBotQueue, budget.globalQueue),
49
+ globalQueue: budget.globalQueue,
50
+ };
51
+ }
24
52
  /** Environment variable the launcher uses to pass `--work-budget` to the plugin. */
25
53
  export const WORK_BUDGET_ENV = 'DSH_BOT_WORK_BUDGET';
26
54
  /**
@@ -41,7 +69,10 @@ function durationMs(value) {
41
69
  }
42
70
  /**
43
71
  * Keep only known, positive, finite budget fields. Unknown keys and bad values
44
- * are dropped (and listed in `ignored`) so a typo never zeroes a cap.
72
+ * are dropped (and listed in `ignored`) so a typo never zeroes a cap or raises
73
+ * it to Infinity. Slot and queue integers above WORK_SLOT_MAX / WORK_QUEUE_MAX
74
+ * are clamped (and listed in `clamped`). Non-integer slot/queue/step values
75
+ * are ignored.
45
76
  * Shorthands: `steps` sets mainMaxSteps and chatMaxSteps; `wall` sets mainWallMs and chatWallMs.
46
77
  * Fields ending in `Ms` accept duration strings such as `30m`.
47
78
  * @param {unknown} input
@@ -49,8 +80,9 @@ function durationMs(value) {
49
80
  export function normalizeWorkBudget(input) {
50
81
  const budget = {};
51
82
  const ignored = [];
83
+ const clamped = [];
52
84
  if (input == null || typeof input !== 'object' || Array.isArray(input))
53
- return { budget, ignored };
85
+ return { budget, ignored, clamped };
54
86
  const raw = { ...input };
55
87
  const expanded = {};
56
88
  if ('steps' in raw) {
@@ -69,14 +101,25 @@ export function normalizeWorkBudget(input) {
69
101
  ignored.push(key);
70
102
  continue;
71
103
  }
72
- const number = key.endsWith('Ms') ? durationMs(value) : Number(value);
104
+ const duration = key.endsWith('Ms');
105
+ const number = duration ? durationMs(value) : Number(value);
73
106
  if (!Number.isFinite(number) || number <= 0) {
74
107
  ignored.push(key);
75
108
  continue;
76
109
  }
77
- budget[key] = Math.floor(number);
110
+ if (!duration && !Number.isInteger(number)) {
111
+ ignored.push(key);
112
+ continue;
113
+ }
114
+ const max = INT_MAX[key];
115
+ if (max != null && number > max) {
116
+ budget[key] = max;
117
+ clamped.push(key);
118
+ continue;
119
+ }
120
+ budget[key] = duration ? Math.floor(number) : number;
78
121
  }
79
- return { budget, ignored };
122
+ return { budget, ignored, clamped };
80
123
  }
81
124
  /**
82
125
  * Parse `--work-budget` / DSH_BOT_WORK_BUDGET: JSON (`{"steps":80,"wall":"30m"}`)
@@ -86,13 +129,13 @@ export function normalizeWorkBudget(input) {
86
129
  export function parseWorkBudget(text) {
87
130
  const source = typeof text === 'string' ? text.trim() : '';
88
131
  if (source === '')
89
- return { budget: {}, ignored: [] };
132
+ return { budget: {}, ignored: [], clamped: [] };
90
133
  if (source.startsWith('{')) {
91
134
  try {
92
135
  return normalizeWorkBudget(JSON.parse(source));
93
136
  }
94
137
  catch {
95
- return { budget: {}, ignored: [source] };
138
+ return { budget: {}, ignored: [source], clamped: [] };
96
139
  }
97
140
  }
98
141
  const object = {};
@@ -109,10 +152,14 @@ export function parseWorkBudget(text) {
109
152
  object[piece.slice(0, eq).trim()] = piece.slice(eq + 1).trim();
110
153
  }
111
154
  const normalized = normalizeWorkBudget(object);
112
- return { budget: normalized.budget, ignored: [...ignored, ...normalized.ignored] };
155
+ return { budget: normalized.budget, ignored: [...ignored, ...normalized.ignored], clamped: normalized.clamped };
113
156
  }
114
157
  /**
115
- * Defaults, then the environment (launcher `--work-budget`), then plugin config `work`.
158
+ * Defaults, then the environment (launcher `--work-budget` / `DSH_BOT_WORK_BUDGET`),
159
+ * then plugin config `work`. Limits are applied when the work runtime is created
160
+ * (process start or plugin load). They are not hot-reloaded into an already
161
+ * running runtime. Lowering a cap never cancels a worker that is already running;
162
+ * later dispatch and promotion use the new caps.
116
163
  * @param {unknown} config
117
164
  * @param {string | undefined} envText
118
165
  */
@@ -122,6 +169,7 @@ export function resolveWorkBudget(config, envText) {
122
169
  return {
123
170
  budget: { ...DEFAULT_WORK_BUDGET, ...fromEnv.budget, ...fromConfig.budget },
124
171
  ignored: [...fromEnv.ignored, ...fromConfig.ignored],
172
+ clamped: [...fromEnv.clamped, ...fromConfig.clamped],
125
173
  };
126
174
  }
127
175
  /**
@@ -211,6 +259,8 @@ export function estimateWorkerBudget(briefing, suggestion, defaults = DEFAULT_WO
211
259
  maxTokens: clampInt(suggestion?.maxTokens, 1000, defaults.workerMaxTokens) ?? guessedTokens,
212
260
  perBot: defaults.perBot,
213
261
  global: defaults.global,
262
+ perBotQueue: defaults.perBotQueue,
263
+ globalQueue: defaults.globalQueue,
214
264
  };
215
265
  }
216
266
  /**
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * File tools for a worker. Plugin-created agents do not inherit the web preset,
3
3
  * so their request header otherwise lists only host tools.
4
- * This preset is tool-fs only: read, write, and edit. It does not add bash,
5
- * and it does not change the sandbox mode or add writable roots.
6
- * The session cwd copied at create remains the workspace-write boundary.
4
+ * This preset mounts official file tools and official command tools
5
+ * (`@deepseek-ai/dsh-tool-bash`, `@deepseek-ai/dsh-tool-jobs`). It does not
6
+ * change the host sandbox mode, add writable roots, or mount the web preset
7
+ * (no web_fetch, subagent, or other profile tools). The session cwd copied
8
+ * at create remains the workspace-write boundary; bash uses the already
9
+ * composed host bash-sandbox and approval policy.
7
10
  */
8
11
  export const WORKER_FILE_PRESET = 'foundations-files';
9
12
  /**
@@ -42,6 +45,8 @@ export function ensureWorkerFilePreset(ctx) {
42
45
  name: '@deepseek-ai/dsh-tool-fs',
43
46
  config: { applyPatch: false, readImage: false },
44
47
  },
48
+ { id: 'tool-bash', name: '@deepseek-ai/dsh-tool-bash' },
49
+ { id: 'tool-jobs', name: '@deepseek-ai/dsh-tool-jobs' },
45
50
  ],
46
51
  })
47
52
  .then(() => WORKER_FILE_PRESET)
package/dist/work-http.js CHANGED
@@ -141,12 +141,36 @@ export function openPageLive(req, res, source) {
141
141
  const intervalMs = source.intervalMs ?? 1000;
142
142
  /** @type {ReturnType<typeof setInterval> | null} */
143
143
  let timer = null;
144
+ let interactionTimer = null;
145
+ let lastInteractions = '';
146
+ let interactionFailed = false;
147
+ const pumpInteractions = () => {
148
+ if (stopped || !source.interactions)
149
+ return;
150
+ try {
151
+ const text = JSON.stringify(source.interactions());
152
+ if (text === lastInteractions && !interactionFailed)
153
+ return;
154
+ interactionFailed = false;
155
+ lastInteractions = text;
156
+ res.write(`event: interactions\ndata: ${text}\n\n`);
157
+ }
158
+ catch {
159
+ // Downgrade the client to REST fallback without closing desk/work updates.
160
+ if (!interactionFailed) {
161
+ interactionFailed = true;
162
+ res.write('event: interaction-error\ndata: {}\n\n');
163
+ }
164
+ }
165
+ };
144
166
  const stop = () => {
145
167
  if (stopped)
146
168
  return;
147
169
  stopped = true;
148
170
  if (timer)
149
171
  clearInterval(timer);
172
+ if (interactionTimer)
173
+ clearInterval(interactionTimer);
150
174
  if (!res.writableEnded)
151
175
  res.end();
152
176
  };
@@ -201,6 +225,11 @@ export function openPageLive(req, res, source) {
201
225
  busy = false;
202
226
  }
203
227
  };
228
+ pumpInteractions();
229
+ if (source.interactions) {
230
+ interactionTimer = setInterval(pumpInteractions, intervalMs);
231
+ interactionTimer.unref?.();
232
+ }
204
233
  void pump();
205
234
  timer = setInterval(() => {
206
235
  void pump();
@@ -136,6 +136,13 @@ export async function pushInput(book, input, deps) {
136
136
  const ticket = book.ticket(input.ticket_id);
137
137
  if (!attempt?.child_session_id || !ticket)
138
138
  return { ok: false, status: 'pending' };
139
+ if (input.kind !== 'cancel_note' &&
140
+ (['failed', 'cancelled', 'delivered'].includes(ticket.status) ||
141
+ ticket.active_attempt_id !== input.attempt_id ||
142
+ ticket.briefing_revision !== input.briefing_revision)) {
143
+ book.markInputFlush(input.id, 'dead', deps.pid, 'ticket-finished-or-superseded', null, false);
144
+ return { ok: false, status: 'dead' };
145
+ }
139
146
  let budget = { wallMs: 600_000, maxTokens: 400_000 };
140
147
  try {
141
148
  budget = { ...budget, ...JSON.parse(ticket.budget_json) };
@@ -23,6 +23,7 @@ export async function startWorkMock(options) {
23
23
  pendingIds: sessionId => world.pendingIds(sessionId),
24
24
  cancel: (sessionId, cancelOptions) => world.cancel(sessionId, cancelOptions),
25
25
  snapshot: sessionId => world.snapshot(sessionId),
26
+ childPresent: sessionId => world.hasSession(sessionId),
26
27
  now,
27
28
  pid: process.pid,
28
29
  });
package/dist/work-mock.js CHANGED
@@ -106,6 +106,12 @@ export function createMockWorld() {
106
106
  async snapshot(sessionId) {
107
107
  return session(sessionId).events.map(event => ({ ...event, data: event.data }));
108
108
  },
109
+ hasSession(sessionId) {
110
+ return sessions.has(sessionId);
111
+ },
112
+ dropChild(sessionId) {
113
+ sessions.delete(sessionId);
114
+ },
109
115
  };
110
116
  /**
111
117
  * @param {string} sessionId