@thready-web/dsh-bot-plugin 0.1.0-beta.3 → 0.1.0-beta.5

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,
@@ -12,15 +18,39 @@ export const DEFAULT_WORK_BUDGET = Object.freeze({
12
18
  chatWallMs: 30 * 60 * 1000,
13
19
  holdMs: 15_000,
14
20
  workerMaxSteps: 8,
15
- workerWallMs: 10 * 60 * 1000,
16
- workerMaxTokens: 400_000,
17
- perBot: 1,
18
- global: 2,
21
+ /** One budget slice. A grant adds another slice; there is no cumulative ceiling. */
22
+ workerWallMs: 30 * 60 * 1000,
23
+ /** One budget slice. A grant adds another slice; there is no cumulative ceiling. */
24
+ workerMaxTokens: 1_000_000,
25
+ perBot: 2,
26
+ global: 4,
27
+ perBotQueue: 8,
28
+ globalQueue: 16,
19
29
  leaseMs: 60_000,
20
30
  starveMs: 30_000,
21
31
  mergeWindowMs: 1_000,
22
32
  });
23
33
  const BUDGET_KEYS = Object.keys(DEFAULT_WORK_BUDGET);
34
+ const INT_MAX = {
35
+ perBot: WORK_SLOT_MAX,
36
+ global: WORK_SLOT_MAX,
37
+ perBotQueue: WORK_QUEUE_MAX,
38
+ globalQueue: WORK_QUEUE_MAX,
39
+ };
40
+ /**
41
+ * A single bot cannot run more workers than the global cap, even if `perBot`
42
+ * is larger. The same applies to the queue caps. Existing running workers are
43
+ * not cancelled when a later process start uses a lower cap.
44
+ * @param {WorkBudget} budget
45
+ */
46
+ export function effectiveWorkLimits(budget) {
47
+ return {
48
+ perBot: Math.min(budget.perBot, budget.global),
49
+ global: budget.global,
50
+ perBotQueue: Math.min(budget.perBotQueue, budget.globalQueue),
51
+ globalQueue: budget.globalQueue,
52
+ };
53
+ }
24
54
  /** Environment variable the launcher uses to pass `--work-budget` to the plugin. */
25
55
  export const WORK_BUDGET_ENV = 'DSH_BOT_WORK_BUDGET';
26
56
  /**
@@ -41,7 +71,10 @@ function durationMs(value) {
41
71
  }
42
72
  /**
43
73
  * 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.
74
+ * are dropped (and listed in `ignored`) so a typo never zeroes a cap or raises
75
+ * it to Infinity. Slot and queue integers above WORK_SLOT_MAX / WORK_QUEUE_MAX
76
+ * are clamped (and listed in `clamped`). Non-integer slot/queue/step values
77
+ * are ignored.
45
78
  * Shorthands: `steps` sets mainMaxSteps and chatMaxSteps; `wall` sets mainWallMs and chatWallMs.
46
79
  * Fields ending in `Ms` accept duration strings such as `30m`.
47
80
  * @param {unknown} input
@@ -49,8 +82,9 @@ function durationMs(value) {
49
82
  export function normalizeWorkBudget(input) {
50
83
  const budget = {};
51
84
  const ignored = [];
85
+ const clamped = [];
52
86
  if (input == null || typeof input !== 'object' || Array.isArray(input))
53
- return { budget, ignored };
87
+ return { budget, ignored, clamped };
54
88
  const raw = { ...input };
55
89
  const expanded = {};
56
90
  if ('steps' in raw) {
@@ -69,14 +103,25 @@ export function normalizeWorkBudget(input) {
69
103
  ignored.push(key);
70
104
  continue;
71
105
  }
72
- const number = key.endsWith('Ms') ? durationMs(value) : Number(value);
106
+ const duration = key.endsWith('Ms');
107
+ const number = duration ? durationMs(value) : Number(value);
73
108
  if (!Number.isFinite(number) || number <= 0) {
74
109
  ignored.push(key);
75
110
  continue;
76
111
  }
77
- budget[key] = Math.floor(number);
112
+ if (!duration && !Number.isInteger(number)) {
113
+ ignored.push(key);
114
+ continue;
115
+ }
116
+ const max = INT_MAX[key];
117
+ if (max != null && number > max) {
118
+ budget[key] = max;
119
+ clamped.push(key);
120
+ continue;
121
+ }
122
+ budget[key] = duration ? Math.floor(number) : number;
78
123
  }
79
- return { budget, ignored };
124
+ return { budget, ignored, clamped };
80
125
  }
81
126
  /**
82
127
  * Parse `--work-budget` / DSH_BOT_WORK_BUDGET: JSON (`{"steps":80,"wall":"30m"}`)
@@ -86,13 +131,13 @@ export function normalizeWorkBudget(input) {
86
131
  export function parseWorkBudget(text) {
87
132
  const source = typeof text === 'string' ? text.trim() : '';
88
133
  if (source === '')
89
- return { budget: {}, ignored: [] };
134
+ return { budget: {}, ignored: [], clamped: [] };
90
135
  if (source.startsWith('{')) {
91
136
  try {
92
137
  return normalizeWorkBudget(JSON.parse(source));
93
138
  }
94
139
  catch {
95
- return { budget: {}, ignored: [source] };
140
+ return { budget: {}, ignored: [source], clamped: [] };
96
141
  }
97
142
  }
98
143
  const object = {};
@@ -109,10 +154,14 @@ export function parseWorkBudget(text) {
109
154
  object[piece.slice(0, eq).trim()] = piece.slice(eq + 1).trim();
110
155
  }
111
156
  const normalized = normalizeWorkBudget(object);
112
- return { budget: normalized.budget, ignored: [...ignored, ...normalized.ignored] };
157
+ return { budget: normalized.budget, ignored: [...ignored, ...normalized.ignored], clamped: normalized.clamped };
113
158
  }
114
159
  /**
115
- * Defaults, then the environment (launcher `--work-budget`), then plugin config `work`.
160
+ * Defaults, then the environment (launcher `--work-budget` / `DSH_BOT_WORK_BUDGET`),
161
+ * then plugin config `work`. Limits are applied when the work runtime is created
162
+ * (process start or plugin load). They are not hot-reloaded into an already
163
+ * running runtime. Lowering a cap never cancels a worker that is already running;
164
+ * later dispatch and promotion use the new caps.
116
165
  * @param {unknown} config
117
166
  * @param {string | undefined} envText
118
167
  */
@@ -122,6 +171,7 @@ export function resolveWorkBudget(config, envText) {
122
171
  return {
123
172
  budget: { ...DEFAULT_WORK_BUDGET, ...fromEnv.budget, ...fromConfig.budget },
124
173
  ignored: [...fromEnv.ignored, ...fromConfig.ignored],
174
+ clamped: [...fromEnv.clamped, ...fromConfig.clamped],
125
175
  };
126
176
  }
127
177
  /**
@@ -183,34 +233,32 @@ export function budgetTrip(input) {
183
233
  return null;
184
234
  }
185
235
  /**
186
- * Positive integer inside an inclusive range.
236
+ * Positive integer at or above `min`. A non-finite value is omitted.
187
237
  * @param {unknown} value
188
238
  * @param {number} min
189
- * @param {number} max
190
239
  */
191
- function clampInt(value, min, max) {
240
+ function clampAtLeast(value, min) {
192
241
  const number = Number(value);
193
242
  if (!Number.isFinite(number))
194
243
  return null;
195
- return Math.max(min, Math.min(max, Math.floor(number)));
244
+ return Math.max(min, Math.floor(number));
196
245
  }
197
246
  /**
198
247
  * Ticket budget chosen when the main bot dispatches.
199
- * An explicit estimate is kept inside the host ceiling. An omitted field is
200
- * derived from the briefing length so every ticket gets its own numbers.
201
- * @param {string} briefing
248
+ * An omitted field is one standard slice. An explicit estimate is kept, with a
249
+ * floor of 1000. Later grants add on top and are not capped by this slice.
250
+ * @param {string} _briefing
202
251
  * @param {{ wallMs?: number, maxTokens?: number } | null | undefined} suggestion
203
252
  * @param {typeof DEFAULT_WORK_BUDGET} defaults
204
253
  */
205
- export function estimateWorkerBudget(briefing, suggestion, defaults = DEFAULT_WORK_BUDGET) {
206
- const chars = typeof briefing === 'string' ? briefing.length : 0;
207
- const guessedWall = Math.min(defaults.workerWallMs, 180_000 + chars * 100);
208
- const guessedTokens = Math.min(defaults.workerMaxTokens, 24_000 + chars * 8);
254
+ export function estimateWorkerBudget(_briefing, suggestion, defaults = DEFAULT_WORK_BUDGET) {
209
255
  return {
210
- wallMs: clampInt(suggestion?.wallMs, 1000, defaults.workerWallMs) ?? guessedWall,
211
- maxTokens: clampInt(suggestion?.maxTokens, 1000, defaults.workerMaxTokens) ?? guessedTokens,
256
+ wallMs: clampAtLeast(suggestion?.wallMs, 1000) ?? defaults.workerWallMs,
257
+ maxTokens: clampAtLeast(suggestion?.maxTokens, 1000) ?? defaults.workerMaxTokens,
212
258
  perBot: defaults.perBot,
213
259
  global: defaults.global,
260
+ perBotQueue: defaults.perBotQueue,
261
+ globalQueue: defaults.globalQueue,
214
262
  };
215
263
  }
216
264
  /**
@@ -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();